【JavaScript】if 的简洁写法| 三元运算子

判断的条件符合条件执行冒号前不符合条件执行冒号后

看 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


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章