【发布时间】:2020-03-30 09:47:17
【问题描述】:
嗨,我是 JS 新手,我正在尝试下面的代码
a=[0,1,3]
if (2 in a){ console.log(a)}
在上面的代码中,我正在检查元素是否可用。但在上述情况下,2 不在数组中,但条件显示为真,为什么?
我知道我们可以像这样检查条件 a.includes(2) 为什么在上述情况下显示为真?
感谢提前。
【问题讨论】:
-
"The in operator returns true if the specified property is in the specified object or its prototype chain."。这里,键“2”是这个数组的一个属性(它是值“3”的索引)
-
0xc14m1z 的答案是正确的 - 您需要使用
a.indexOf(2) !== -1来检查2是否在a中。小心使用.includes(),IE不支持