I'm trying to check if an elements already exists in an array. I know of at least 2 different ways to do so: [1] and [2].
I tested both of them, but get no
in both cases:
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")
}
In both cases I get no
. Am I missing something?
Also, which of them is faster?
Answer
Both of those are doing the almost the same thing: Checking if myArray
has a property called "Banana"
, which it doesn't; it has keys 0,1,2,
and 3
, and the value at myArray[0]
happens to be "Banana".
If you want to check if a string is in an array you can use Array.prototype.indexOf:
if( myArray.indexOf("Banana") >= 0 ) {
console.log("yes")
} else {
console.log("no")
}
No comments:
Post a Comment