?
符合條件執行冒號前:
不符合條件執行冒號後看 w3c setInterval() 的範例時學習到的三元運算子概念
const myInterval = setInterval(setColor, 500);
function setColor() {
let x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}
function stopColor() {
clearInterval(myInterval);
}
背景顏色如果是黃色的話,顏色改為粉色;不是黃色的話改為黃色。x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
後半段的判斷條件
x.style.backgroundColor == "yellow" ? "pink" : "yellow";
document body 的背景顏色是不是黃色?
true ➡️ "pink"
false ➡️ "yellow"
前半段指定樣式到 document body
x.style.backgroundColor = "pink"
x.style.backgroundColor = "yellow"
都是以問號/冒號判別條件
function findGreaterOrEqual(a, b) {
if(a === b) {
return "a and b are equal";
}
else if(a > b) {
return "a is greater";
}
else {
return "b is greater ";
}
}
// 三元運算子
function findGreaterOrEqual(a, b) {
return (a === b) ? "a and b are equal" : (a > b) ? "a is greater" : "b is greater";
}
參考來源:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_setinterval_clearinterval2
https://medium.com/@kyokyox2/js-%E4%B8%89%E5%85%83%E9%81%8B%E7%AE%97%E7%AC%A6-%E4%B8%89%E5%85%83%E9%81%8B%E7%AE%97%E5%80%BC-3987be9623a5