Check For Element In Array
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 myAr
Solution 1:
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")
}
Post a Comment for "Check For Element In Array"