JavaScript如何用单个if判断字符串非apple且非orange?
问题解决:用单个if实现“既不是apple也不是orange”的判断
你遇到的问题核心是逻辑运算符用错了:用||(逻辑或)的时候,只要任意一个条件成立整个表达式就为真,这就导致不管fruit是apple还是orange,条件都会满足——比如当fruit是apple时,fruit != "orange"是true,整个||表达式就为true;当fruit是orange时,fruit != "apple"是true,表达式也为true,所以所有元素都会被输出,这显然不符合你的需求。
正确的做法是用&&(逻辑与),因为你需要同时满足既不是apple并且不是orange这两个条件,对应的条件表达式是:
if(fruit != "apple" && fruit != "orange")
修改后的完整代码如下:
const fruits = ["apple","orange","banana","cherry"]; fruits.forEach(function(fruit){ if(fruit != "apple" && fruit != "orange"){ console.log(fruit + " is not apple or orange"); } });
运行这段代码后,只会输出banana is not apple or orange和cherry is not apple or orange,和你嵌套if的实现效果完全一致。
另外,你也可以用数组包含的方式来简化判断,写法更简洁,尤其是当需要排除的元素更多时可读性更强:
if(!["apple", "orange"].includes(fruit))
内容的提问来源于stack exchange,提问作者Ronnie Smith
相关产品推荐
相关产品推荐

