Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable in for loop is a string [duplicate]

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++)?

like image 584
abfarid Avatar asked Aug 16 '16 22:08

abfarid


1 Answers

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 }  
like image 90
Derek Pollard Avatar answered Oct 05 '22 16:10

Derek Pollard