-2

I am a beginner at JavaScript (beginner as in studying for about a week) and I'm stuck on how I can check if an array contains a certain string. Here I've made a word-guessing game.

I declare the function 'contains' like this:

function contains(thing, array){
  if(thing in array){
    return true;
  }
  else {
    return false;
  }
};

I'm not sure what I'm doing wrong, but the value is always false.

The function uses the third technique here. But I've also tried using the accepted technique here, both with the same result.

Any help is greatly appreciated!

Community
  • 1
  • 1
  • use the [indexOf](http://www.w3schools.com/jsref/jsref_indexof_array.asp) method of arrays. – Syntac Oct 08 '16 at 20:30
  • 2
    Please paste your code *(a minimal reproduction of the non-working part)* here so that we don't need to visit another site, and so that your question will make sense if that link ever dies. –  Oct 08 '16 at 20:31

2 Answers2

2

Had to make a separate answer to make sure this is clear. The correct approach to see if something is in an array:

var myArr = ['apples', 'bananas', 'pears'];

if (myArr.indexOf('pears') > -1) { // myArr.indexOf('pears') will equal the number 2
    console.log('we got pears'); // this will log
}

if (myArr.indexOf('hotdogs') > -1) { // since it's not in the array, it's -1
    console.log('hotdog!'); // this will not log
}

Finally please note that a for...in loop actually should not be used to iterate over arrays -- it really exists to iterate over keys in an object. For iterating over arrays in JS, a classic for loop is the correct approach.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
0

Use the indexOf method.
The in operator checks for the existence of keys, not of values.
You, as well, can use a for..in loop, to iterate over all keys of an object:

for (key in object)
    console.log(object[key])

In the case of arrays, it would give the same result as

for (index=0; index<array.length; index++)
    console.log(array[i])
Syntac
  • 1,687
  • 11
  • 10
  • `for-in` is used for general property enumeration, which can include arrays, but generally is avoided for that purpose. The `in` operator is used for checking existence of a property. I can't tell which you're referring to in your answer. –  Oct 08 '16 at 20:34
  • And two of the OP's links refer to `.indexOf()`, so more specific help is needed. –  Oct 08 '16 at 20:36
  • 1
    @Syntac-- correct on needing to use indexOf -- however, please note that a `for...in` loop actually should not be used to iterate over arrays -- it really exists to iterate over keys in an object. For iterating over arrays in JS, a classic `for` loop is the correct approach. – Alexander Nied Oct 08 '16 at 20:36
  • `for-in` is not "the same as" `for`. There are important differences. However, the OP is actually doing `if(thing in array){`, which is about property checking, not iteration. –  Oct 08 '16 at 20:38