drets
drets

Reputation: 2805

for...in with array outputs strings instead of numbers

var xs=[]; for (var i in [1,2,3]) xs.push(i); console.log(xs);

Why ["0", "1", "2"] and not [0, 1, 2]?

I have the hunch that this is due to array internal implementation.
Array in javascript may be seen as {"0":1, "1":2, "2":3}?

EDIT: I write a compiler. I don't care that I don't need to use for in and arrays. I don't care about readability of the line. I'd like to know why the keys of the array object are strings and not numbers. Any statements from specification would be appreciated.

Upvotes: 0

Views: 67

Answers (2)

31piy
31piy

Reputation: 23859

The problem:

for...in loop is not meant to iterate over an array, but was designed to enumerate the object keys. Per the docs on MDN:

for...in should not be used to iterate over an Array where the index order is important.

If used with the arrays, the loop treats the array like an object, and considers the indices as the keys (so the stringified keys are printed).

The quick fix:

The problem with you code is that the statement for (var i in [1,2,3]) yields the array indices as i in the loop body. You may try a simple fix in the loop body:

var xs=[]; for (var i in [1,2,3]) xs.push([1,2,3][i]); console.log(xs);

You may want to extract [1,2,3] in a variable to get the code more readable.

The recommended fix:

Use Array#forEach instead. It is specifically designed to loop over arrays, and is stable across all environments.

var xs=[]; [1,2,3].forEach(item => xs.push(item)); console.log(xs);

Upvotes: 3

blue112
blue112

Reputation: 56522

Don't loop with in on an array.

Loop with of :

 var xs=[];
 for (var i of [1,2,3]) xs.push(i);
 console.log(xs);

Basically, in loops on object keys, and of loops on array value. The "0" "1" and "2" are keys.

Upvotes: 4

Related Questions