10

Possible Duplicate:
array.contains(obj) in JavaScript

Let's say I have an array = [0,8,5]

What is the fastest way to know if 8 is inside this one.. for example:

if(array.contain(8)){
 // return true
}

I found this : Fastest way to check if a value exist in a list (Python)

and this : fastest way to detect if a value is in a set of values in Javascript

But this don't answer to my question. Thank you.

2

4 Answers 4

10

Use indexOf() to check whether value is exist or not

array.indexOf(8)

Sample Code,

var arr = [0,8,5];
alert(arr.indexOf(8))​; //returns key

Update

For IE support

//IE support
if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}

var arr = [0,8,5];
alert(arr.indexOf(8))
Sign up to request clarification or add additional context in comments.

10 Comments

This of course assumes you're not using an old browser.
Array.indexOf doesn't work in IE < 9.
@MuthuKumaran: That's because that fiddle is using MooTools. MooTools adds Array.prototype.indexOf if it doesn't exist.
+1: MDC also recommends a more elaborate implementation though developer.mozilla.org/en-US/docs/JavaScript/Reference/…
|
4

You can use a indexOf() function

var fruits = ["a1", "a2", "a3", "a4"];
var a = fruits.indexOf("a3");

The output will be: 2

2 Comments

Array.indexOf doesn't work in IE < 9.
Refer this answer for ie < 9 browser stackoverflow.com/questions/1744310/…
0

You can use indexOf or you can try this:

$.inArray(value, array)

Comments

-1

phpjs has a nice php's in_array function's port to javascript, you may use it

http://phpjs.org/functions/in_array/

see example:

in_array('van', ['Kevin', 'van', 'Zonneveld']);

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.