-2

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?

Here is a fiddle.

0

2 Answers 2

8

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")
}
Sign up to request clarification or add additional context in comments.

6 Comments

Why not close the question as a duplicate?
arrays have elements. properties are possible, but 'banana'is no property, just an element.
@ZachSaucier The duplicate describes how to check, but not why the OPs methods didn't work.
The question is quite the same
@NinaScholz I think you're saying the same thing as I did in my answer? Checking for the property called "Banana" is failing because the array doesn't have a property called "Banana", just an element.
|
0

You are, in both cases, looking for the bananath (+1) element of the array, which is not correct.

Either way, the first one should not be used (even if it served to this purpose) because it is not intended to be used with arrays, since it will look for properties.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.