第二周筆記 (JS) -2


Posted by RafealChen on 2021-04-27

基礎

判斷式

if else

if (條件){
    執行
} else if () {
    執行
}else {
    執行
}

/*
多行註解
*/

switch case 選擇太多種

var month = 1
switch(month){
    case 1:
        console.log("一月")
        break
    case 2:
        console.log("二月")
        break
    case 3:
        console.log("三月")
        break
    case 4:
        console.log("四月")
        break
    default:
        console.log("hey")
}
var month_to_chinese = ["一月", "二月", "三月"]
console.log(month_to_chinese[month-1])

ternary 三元運算子

var score = 60
var isPass = false
if (score >= 60){
    isPass = True
} else {
    isPass = false
}

可簡化成
var score = 60
var isPass = (score >= 60)

but
var score = 60
var message = ""
if (score >= 60){
    message = "pass"
} else {
    message = "fail"
}
無法簡化 可使用三元運算子
condition (ex:a>b) ? (true 回傳 a : false回傳 b)
console.log(10 > 5 ? "bigger" : "smaller")
上面範例可改成:
var score = 80
var message = score >= 60 ? "pass" : "fail"

迴圈 loop

do while

var i = 1
do {
    console.log(i)
    i++
} while(i <= 100) // 只要while這邊是true 就會回到do
console.log("i=", i)
或是
var i = 1
do {
    console.log(i)
    i++
    if (i>100) {
        break
    }
} while(true)

break 直截跳除來
continue  跑到下一圈

在瀏覽器上

<script>
debugger // 直接在chrome上用來幫助除錯
var i = 1
do {
    console.log(i)
    i++
} while(i <= 100) // 只要while這邊是true 就會回到do
console.log("i=", i)
</script>

while 迴圈

var i = 1 //初始值
while(i <= 100) { // 終止條件
    console.log(i++) // i 每一圈要做的事情
}

for loop

for (初始值;終止條件;i每一圈要做的事情){

}

array的情況
var scores = [1,2,3,4,5]
for (var i = 0; i < scores.lenth; i++){
    console.log(scores[i])
}









Related Posts

[Leetcode in Java] 27. Remove Element

[Leetcode in Java] 27. Remove Element

Chucker --- View the interaction between the app and the api

Chucker --- View the interaction between the app and the api

[Day 1] JS in Pipeline - DevOps for Local Development Environment (1)

[Day 1] JS in Pipeline - DevOps for Local Development Environment (1)


Comments