5

Possible Duplicates:
Javascript - array.contains(obj)
Best way to find an item in a JavaScript Array ?

I want to check, for example, for the word "the" in a list or map. Is there is any kind of built in function for this?

Community
  • 1
  • 1
Ant's
  • 13,545
  • 27
  • 98
  • 148

2 Answers2

5

In javascript you have Arrays (lists) and Objects (maps).

The literal versions of them look like this:

var mylist = [1,2,3]; // array
var mymap = { car: 'porche', hp: 300, seats: 2 }; // object

if you which to figure out if a value exists in an array, just loop over it:

for(var i=0,len=mylist.length;i<len;i++) {
  if(mylist[i] == 2) {
     //2 exists
     break;
   }
}

if you which to figure out if a map has a certain key or if it has a key with a certain value, all you have to do is access it like so:

if(mymap.seats !== undefined) {
  //the key 'seats' exists in the object
}

if(mymap.seats == 2) {
  //the key 'seats' exists in the object and has the value 2
}
Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
5

Array.indexOf(element) returns -1 if element is not found, otherwise returns its index

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130