Domanda

I noticed that in Javascript a variable used as the index in a for..in loop will be always a string even if I define it the following way:

var s_array = new Array();
s_array[0] = 'foo';
s_array[1] = 'bar';

for(i in s_array){
 alert(typeof(i)); // String
}

Why is it considered a string and not a number?

È stato utile?

Soluzione

The for(x in y) syntax is intended to iterate over the properties of an object (not the indexes of an array), and property names are always stored as strings.

The fact that it also works for arrays is a side effect of array elements being properties on the array object.

To understand the difference, consider this code:

var s_array = new Array();
s_array[0] = 'foo';
s_array[1] = 'bar';
s_array['foo'] = 'bar';

console.log("Object:");
for(i in s_array) {
 console.log(i);   
}
console.log("Array:");
for(var i = 0, l = s_array.length; i < l; i++) {
 console.log(i);   
}

which provides the following output:

Object:
0
1
foo
Array:
0
1

There's a foo property on the object, but it's not actually an element inside the array.

Altri suggerimenti

Arrays are essentially objects with managed set of indexed keys.

Since every key in an object is of type string hence it is a string as well.

Consider your array as :

{"0" : "foo" , "1" : "bar"}

So your

for(i in s_array){ alert(typeof(i)); }

can be read as

for each key in the s_array

In js arrays are high-level, list-like objects (associative arrays).

indexes eventually gets coerced into a string by the JavaScript engine, anyway, through an implicit toString conversion.

source: MDN

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top