operador javascript "en"

I'm used to python, so

a = [1,2,3]
1 in a # -> True
b = ["1", "2", "3", "x"]
"x" in b # -> True

Why is it that in JavaScript

a = [1,2,3]
1 in a // -> true
b = ["1", "2", "3", "x"]
"x" in b // -> false

and much weirder

"1" in b // -> true

preguntado el 09 de marzo de 12 a las 14:03

Podría ser un duplicado de stackoverflow.com/questions/237104/… -

5 Respuestas

in works on KEYS of arrays, not values. 1 in a succeeds because there is an element #1 in your array, which is actually the 2 .

"1" fails, because there is no 1 PROPIEDAD or KEY en su matriz.

Detalles aquí: https://developer.mozilla.org/en/JavaScript/Reference/Operators/in

respondido 09 mar '12, 14:03

Hay array.indexOf, but it's a newer JS feature and won't be in older implementations. - Marc B

The thing you have to understand about JavaScript is almost everything is an "Object" that can have properties. Array's are just a special type of object whose properties are integer indexes and have push, pop, shift, unshift, etc. methods. Plus they can be defined with the square bracket shorthand you used:

a = [1,2,3];

This creates an Array object with the properties:

a[0] = 1;
a[1] = 2;
a[2] = 3;

Now as others have said, all the in operator does is check that an object has a property of that name and a[1] == 2 por lo tanto 1 in a == true. Por otra parte,

b = ["1", "2", "3", "x"];

created an Array object with the properties:

b[0] = "1";
b[1] = "2";
b[2] = "3";
b[3] = "x";

So b["x"] == undefined por lo tanto "x" in b == false.

The other thing you have to understand is JavaScript uses "duck typing", meaning if it looks like a number, JavaScript treats it like a number. In this case, b["1"] == 2 por lo tanto "1" in b == true. I'm not 100% certain whether this is duck typing at work or JavaScript just always treats property names as Strings.

If you wanted to declare a generic object that wouldn't have the Array methods but had the same properties you would write:

var b = {"0": "1", "1": "2", "2": "3", "3": "x"};

Que es la abreviatura de:

var b = {}; // This declares an Object
b[0] = "1";
b[1] = "2";
b[2] = "3";
b[3] = "x";

respondido 09 mar '12, 15:03

Porque "x" in b is looking for a property name 'x'. There is none, they are all numerical (but still string) property names, considering it is an array.

respondido 09 mar '12, 14:03

1 is a valid vanilla numeric array index, x is not; in works with array indexes/object member names, not their values.

respondido 09 mar '12, 14:03

"1" is not a property of the array object...

respondido 09 mar '12, 14:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.