Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the typeof a numerical array index in a "for..in" loop considered a string? [duplicate]

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?

like image 473
talsibony Avatar asked Dec 11 '22 10:12

talsibony


2 Answers

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.

like image 185
Anthony Grist Avatar answered Dec 28 '22 07:12

Anthony Grist


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

like image 25
loxxy Avatar answered Dec 28 '22 08:12

loxxy