Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for loop var "i" is treated as a string?

I am using Titanium to build some mobile apps and I noticed that this will give a result that I wasn't expecting.

data = ['a','b', 'c','d'];

for (var i in data){
    Ti.API.debug(i+1);
};

This will print: 01,11,12,13

Is this something particular to Titanium or is it generally in Javascript?

Why isn't 'i' being treated as an integer? I am very confused.

Thanks for your help.

like image 453
Leonardo Amigoni Avatar asked Mar 21 '26 20:03

Leonardo Amigoni


2 Answers

This doesn't directly answer your question, but if you are looping through an array you should not use for (var i in data). This loops through all members of an object, including methods, properties, etc.

What you want to do is this:

for (var i=0, item; i<data.length; i++) {
    item = data[i];
}
like image 155
Francis Avila Avatar answered Mar 23 '26 11:03

Francis Avila


data is an array, so you use a for loop, not a for-in loop:

var data = [ ... ];
var i;

for ( i = 0; i < data.length; i += 1 ) {
    Ti.API.debug( i + 1 );
}

Alternatively, you can use the forEach array method:

data.forEach( function ( val, i ) {
    Ti.API.debug( i + 1 );
});
like image 32
Šime Vidas Avatar answered Mar 23 '26 11:03

Šime Vidas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!