You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

两个JavaScript if条件是否等价?求更优条件写法

问题解答

Case 2与Case 1是否等价?

完全不等价。

在JavaScript中,'firstName' || 'lastName'会执行逻辑或运算:由于'firstName'是非空字符串(属于真值),运算会直接返回'firstName',不会再判断后面的'lastName'。因此Case 2的代码实际上等价于:

if (selectedItem === 'firstName') {
  ...
}

这和Case 1中同时判断selectedItem等于firstName或lastName的逻辑完全不符,会漏掉对lastName的校验。

更优的条件写法

可以使用数组的includes()方法,代码更简洁易读,后续新增判断项时也更方便维护:

if (['firstName', 'lastName'].includes(selectedItem)) {
  ...
}

内容的提问来源于stack exchange,提问作者Federick J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 09:15:47