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){
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
.lengthproperty 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:
Now add something to the
prototypeobject of its constructor function:If you use a
for-instatement, you’ll end up hitting thesayHellofunction 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
forstatement.