Possible Duplicate:
for(var i in aArray) VS for(i=0; i<aArray.length; i++)
Is it safe to assume that these will always do the same thing, and that I should always use the latter?
for (var i = 0; i < a.length; i++){
for (var i in a){
Possible Duplicate:
for(var i in aArray) VS for(i=0; i<aArray.length; i++)
Is it safe to assume that these will always do the same thing, and that I should always use the latter?
for (var i = 0; i < a.length; i++){
for (var i in a){
No it isn't safe, because they're not the same thing.
The first iterates numeric indices up until whatever value is stored in the .length
property in numeric order.
The second enumerates all enumerable properties on an object, including prototyped properties, and doesn't guarantee any sort of order.
Take an Array:
var arr = ['a','b','c'];
Now add something to the prototype
object of its constructor function:
Array.prototype.sayHello = function() { alert('hi'); };
If you use a for-in
statement, you'll end up hitting the sayHello
function instead of just the numeric indices.
If you're dealing with objects that don't have enumerable properties aside from the indices, and you don't care about the order, then it really won't matter I guess, but the proper form is still to use a for
statement.
No, because (assuming in the first version you use i
to index a
) arrays can have non-integer indexes. So if you had:
a = {1:1, 'f': 'hey'}
In the first version, i
would be 0
then 1
. You'd try first to index a
with 0
and not get anything back because 0
isn't a valid index, then try with 1
and get 'hey'. So you can see this is clearly wrong.
The second one will go over every index no matter what it is.
So the first version assumes all the indices are numeric and in order, whereas the second will iterate every index no matter what it is.
No.
Use the former for arrays when you need to enumerate through the natural order of an array. Use the latter for objects, when the ordering is unimportant or inexistant.