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?

2
  • See the linked question for some very good answers. Commented Mar 9, 2011 at 12:21
  • 1
    Javascript doesn't have "lists" or "maps". It has arrays and objects. Commented Mar 9, 2011 at 12:27

2 Answers 2

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

Comments

5

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

1 Comment

The indexOf() method is not supported in Internet Explorer 8 and earlier.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.