iT邦幫忙

1

【JavaScript】if 的簡潔寫法| 三元運算子

7514 2022-01-13 16:27:581211 瀏覽
  • 分享至 

  • xImage
  •  

判斷的條件符合條件執行冒號前不符合條件執行冒號後

看 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";

  1. 後半段的判斷條件
    x.style.backgroundColor == "yellow" ? "pink" : "yellow";
    document body 的背景顏色是不是黃色?
    true ➡️ "pink"
    false ➡️ "yellow"

  2. 前半段指定樣式到 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


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言