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++)
?
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.
parseInt(i)
works in this situation, but for good programming practice, you would want to use a for
loop that looks similar to this:
var array = [1, 2, 3]; for (var i = array.length - 1; i >= 0; i--) { // do work with each array element here }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With