Javascript, The fastest way to find out if there is a specific value in an array?

Possible duplicate:
array.contains (obj) in JavaScript

Say I have an array = [0.8.5]

What is the fastest way to find out if inside this 8? For instance:

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

I found this: The fastest way to check if a value exists in a list (Python)

and this: the fastest way to determine if a value is in a set of values ​​in Javascript

But this does not answer my question. Thanks.

+6
source share
4 answers

Use indexOf() to check if a value exists or not

 array.indexOf(8) 

Code example

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

Update

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)) 
+8
source

You can use the indexOf () function

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

The output will be: 2

+4
source

You can use indexOf , or you can try the following:

 $.inArray(value, array) 
0
source

phpjs has a nice PHP port in_array function for javascript, you can use it

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

see example:

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

All Articles