判断的条件?
符合条件执行冒号前:
不符合条件执行冒号后
看 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