【JavaScript】條件語句
阿新 • • 發佈:2020-07-10
以下內容為學習記錄,可以參考 MDN 原文。
環境
- vscode 1.46
- Microsoft Edge 83
條件判斷語句
人類(以及其他的動物)無時無刻不在做決定,這些決定都影響著他們的生活,從小事(“我應該吃一片還是兩片餅乾”)到重要的大事(“我應該留在我的祖國,在我父親的農場工作;還是應該去美國學習天體物理學”)。
if 語句
let a = 3;
if(a === 3){
console.log("相等");
}
if...else 語句
let a = 3; if(a === 3){ console.log("相等"); }else{ console.log("不相等"); }
if...esle if 語句
let a = 3;
if(a === 3){
console.log("等於三");
}else if(a === 4){
console.log("等於四");
}
邏輯運算子
邏輯與(&&)、邏輯或(||)、非(!),邏輯與表示兩個都為真才為真,邏輯或有一個為真就為真,非是取反。
let a = 3;
if(a === 3 || a === 4){
console.log("等於三或者等於四");
}
switch 語句
if...else 語句能夠很好地實現條件程式碼,但是它們不是沒有缺點,它們主要適用於您只有幾個選擇的情況。
對於只想將變數設定一系列為特定值的選項或根據條件列印特定語句的情況,
語法可能會很麻煩,特別是如果您有大量選擇。
let choice = 'snowing'; switch (choice) { case 'sunny': para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.'; break; case 'rainy': para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.'; break; case 'snowing': para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.'; break; case 'overcast': para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.'; break; default: para.textContent = ''; }
三元運算子
let a = 3;
let result = a === 3? "相等":"不相等";