For my opinion , don't use for/in for array.
Because some lib will extends the Array.prototype , the function will
be iterate when you doing for-in on it.
for example , the following statement could explain the different
between you use for-in and using index.
(test it with firebug.:p )
====================
Array.prototype.$indexOf=function (a) { return jQuery.inArray(a, this); };
var k =[1,2,3];
for(a in k){
console.log(a+":"+k[a]); //you will get $indexOf for additional
in this case.
}
for(var i=0,len=k.length;i<len;++i){ //it's correct here.
console.log(i+":"+k[i]);
}
==================
2011/3/11 Alex <[email protected]>:
> I'm struggling to find something very simple.
>
> Question 1:
> If I have an array of integers and I use a for-in construct, do I get
> them in the same order they are present inside array?
>
> ex:
> var v = [1,2,3,4]
> for(var i in v){
> print(i + '-->' + v[i]);
> }
>
> is this similar to
> for(var i=0;i<v.length; i++){
> print(i + '-->' + v[i]);
> }
>
> From what I know (and saw in ECMA 262) for-in returns the properties
> of an object and does not guarantee the order of the properties....so
> the answer seems to be "no" - those 2 constructs are not equivalent.
> (from this point of view)
>
> Question 2:
> If you can use both first and second construct does it means that the
> indices of the vector are both properties (of object Array) and
> indices of the array?
>
>
> --
> To view archived discussions from the original JSMentors Mailman list:
> http://www.mail-archive.com/[email protected]/
>
> To search via a non-Google archive, visit here:
> http://www.mail-archive.com/[email protected]/
>
> To unsubscribe from this group, send email to
> [email protected]
>
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]