我试图检查数组中是否已经存在元素。我知道至少有两种不同的方式:[1]和[2]。检查数组中的元素
我测试了他们两个,但在这两种情况下得到no
:
var myArray = ["Banana", "Orange", "Apple", "Mango"];
if ("Banana" in myArray) {
console.log("yes")
} else {
console.log("no") // <--
}
if (typeof myArray["Banana"] === 'undefined') {
console.log("no") // <--
} else {
console.log("yes")
}
在这两种情况下,我得到no
。我错过了什么吗?
另外,哪个更快?
为什么不把问题作为重复来解决? –
数组有元素。属性是可能的,但“香蕉”没有财产,只是一个元素。 –
@ZachSaucier重复描述如何检查,但不是为什么OPs方法不起作用。 – Paulpro