2011-06-15 23 views
23

posibles duplicados:
Test for value in Javascript Array
Best way to find an item in a JavaScript Array ?
Javascript - array.contains(obj)JavaScript si en x

lo general programa en Python, pero recientemente han comenzado a aprender JavaScript.

en Python esto es perfectamente válida si la declaración:

list = [1,2,3,4] 
x = 3 
if x in list: 
    print "It's in the list!" 
else: 
    print "It's not in the list!" 

pero he tenido poblems haciendo lo mismo en Javascript.

¿Cómo se comprueba si x está en la lista y en JavaScript?

+2

http://stackoverflow.com/questions/237104/javascript-array -containsobj –

Respuesta

30

Utilice indexOf que se introdujo en JS 1.6. Tendrá que usar el código que figura en "Compatibilidad" en esa página para agregar compatibilidad con los navegadores que no implementan esa versión de JS.

JavaScript tiene un operador in, pero prueba las claves y no valores.

12

en JavaScript puede utilizar

if(list.indexOf(x) >= 0) 

P.S .: sólo está soportado en los navegadores modernos.

+0

Solo en navegadores modernos. –

+0

@ T.J - Punto tomado. ¿Qué navegadores no son compatibles con esto? –

+0

No sé la lista completa, pero falta en IE8 y abajo (sí, realmente). Microsoft finalmente lo agregó a IE9. Creo que los otros mayores lo han tenido durante años, no conocerían algunos de los navegadores móviles (Blackberry, etc.). Pueden consultar [aquí] (http://jsbin.com/uzama4/3). –

4

de una manera más genric que puede hacer así-

//create a custopm function which will check value is in list or not 
Array.prototype.inArray = function (value) 

// Returns true if the passed value is found in the 
// array. Returns false if it is not. 
{ 
    var i; 
    for (i=0; i < this.length; i++) { 
     // Matches identical (===), not just similar (==). 
     if (this[i] === value) { 
      return true; 
     } 
    } 
    return false; 
}; 

continuación, llamar a esta función en esta manera-

if (myList.inArray('search term')) { 
    document.write("It's in the list!") 
} 
Cuestiones relacionadas