2

I want to be able to see if "megan" is a part of the array people. Though, i can only do this by using people[2].

Here is my code:
var people = new Array("jack","ian");
document.write(people[0]);
people.push("megan");
document.write("<br />");
igetstuckalot
  • 237
  • 2
  • 8
  • 16

1 Answers1

1

Use the indexOf method of the array:

if(people.indexOf("megan") > -1) {
    //do stuff
} else {
    //not in array
}

If the string is in the array, 0 is returned. if not, -1 is returned.

millerbr
  • 2,951
  • 1
  • 14
  • 25
  • No problem at all. Please accept the answer if this was the solution to your problem, so that future people on the site who come to this question know to use my code – millerbr Feb 20 '16 at 23:48
  • This is correct. But you can also use a for loop instead of indexOff: for(var i; i < people.length; i++){ if(people['']== "megan"){ //Megan is found } } The thing with indexOff is that it is slower as stated: http://stackoverflow.com/questions/6682951/why-is-looping-through-an-array-so-much-faster-than-javascripts-native-indexof – Bigalow Feb 20 '16 at 23:51