abfarid abfarid - 1 year ago 74
Javascript Question

Variable in for loop is a string

I'm not sure if this is normal behavior, but running this:

for (var i in [1, 2, 3]) {
console.log(i + 1);

Results in this:

// 01
// 11
// 21

Could somebody please explain, why is
var i
being treated like a string in this situation and not if I do
for (var i = 0; i < [1, 2, 3].length; i++)

You You
Answer Source

Its most likely because in this for loop style (for..in), it is treating i as a key, and since keys in objects are usually strings (yes, an array is a type of object in javascript), it is treating it as a String.

Try using parseInt(i);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download