我应该将哪个for循环用于JavaScript数组和对象?

Which for loop should I use for JavaScript arrays and objects?

本问题已经有最佳答案,请猛点这里访问。

循环访问对象属性时,我总是使用for (i=0; i when looping through arrays.

I always use for (var i in object)

我不能将for (i=0; ... )用于对象属性,但可以将for (var in ...)用于数组,因为数组也是对象。

我要问的问题是:我应该完全转储for (i=0; ... )并对数组和对象使用for (var in ...)?是否有性能冲击?为什么我要用一个而另一个?


(P)I made a JSPER for you:(p)(P)http://jspur.com/for-vs-for-in43(p)(P)Basicly,it is testing performance and you can see a huge performance drop when using EDOCX1.(p)(P)那是你说的,你没有放弃EDOCX1的音乐剧(p)


布尔奇1(P)You should't.EDOCX1.When used to loop arrays doesn't care about the index and it will list properties attached to the object as well.Stick to EDOCX1 theocx1 plus 1 for arrays and EDOCX1 commercial 0 for objects.(p)(P)An excerpt from the MDN:(p)布尔奇1(P)As for the performance,I would uldn't worry about i t,because EDOCX1 universal 0 to loop indexed arrays is obviously not recommended.(p)


(P)如果你想有一个最快的责任守则:(p)(P)对于连续体的爱德华X1音标9和爱德华X1音标10(p)(P)In object arrays you can only use for in…但是,如果你的法典是好的,它不会很容易让你通过一个目标。(p)(P)快速通道:(p)字母名称(P)搜身拖把是另一件重要的事情,以保持法典的速度。(p)字母名称(P)当老年人布朗瑟的时尚之旅…In new browsers it looks like the for loop is a little faster.(p)字母名称(P)Now if u wanna definition variables,do that before you loop.(p)(P)There is also a nice comparation that shows you the performance even if sometimes the Code is not written very well.(p)(P)http://jsper.com/fors-vs-while/61(p)(P)So if you plan to loop through an array always use while-or for(var I=0)..(p)(P)Another loop that I really like U have arrays in multiple objects like JSon is this one(p)字母名称(P)Another mistake that most ppl do is they use push in a loop…执行在一个loop means或执行新的职能的每一次。As we already have"I"that is a index we can set that and use it to store the data directly without executing a new function(p)(P)So(p)字母名称(P)PS.:Feel free to correct my bad English but don't touch the code!否(p)


布尔奇1(P)你应该使用EDOCX1作为另一个国家。(p)(P)但你可以使用EDOCX1,拼写8,将目标的钥匙列为一个阵列,他们使用的是(p)字母名称


(P)Note also that the order of listation is not guaranteed,so for…in on an array may return values out of sequence.It will also list all properties,including those that are not numeric(i.e.would not be returned by iterating over an index)and listable properties on the object's EDOCX1 indicatual 11-chain,so you must always use it with a hasownproperty test if you only want own properties(the most common case).(p)(P)如果你使用一个ES5 host,他们有方法像目标.Getownpropertynames and object.keys to get own properties。但是,Again,Order is not guaranteed.(p)(P)最后,为了、为了和While loops are highly optimed,there is very little difference in performance and what is faster in one browser may be slow in another.Just use what suits and optimise only if performance is an issue.(p)