- 當數組長度 爲 100000時,偶爾能刷出時間相等
- 當數組長度 小於 100000時,差距不明顯,for 與 forEach 誰快誰慢不必定
- 當數組長度 大於 100000時,明顯for 要快於forEach
forEachhtml
- forEach沒法遍歷對象
- forEach沒法在IE中使用,只是在firefox和chrome中實現了該方法
- forEach沒法使用break,continue跳出循環,使用return時,效果和在for循環中使用continue一致
總結:git
- for in , $.each , $().each 既支持對象也支持數組遍歷;
- for , do/while , forEach 只支持數組;
- Array.prototype.map, Array.prototype.every 只支持數組和形似數組的對象;
- forEach不能退出循環,只能經過return來進入到下一個元素的遍歷中(至關於for循環的continue), 且在IE沒有實現該方法;
- $.each和$().each循環只能經過return false 來退出循環, 使用return 或 return true 將跳過一個元素, 繼續執行後面的循環.
for...of
循環能夠使用的範圍包括數組、Set 和 Map 結構、某些相似數組的對象(好比arguments
對象、DOM NodeList 對象)、後文的 Generator 對象,以及字符串。
各時間用的時間大概順序:github
ffor ~= do while < forEach ~= map ~= every < $.each < $(e).each < for inchrome
根據統計數據, 可得這8個方法的運行速度大體排序爲:數組
- for 與 do while
- forEach map every (這3個不相上下,可認爲運行速度差很少)
- $.each
- $(e).each
- for in
github地址(親測):https://caraxiong.github.io/js-demo/tpls/knowledge/for.htmlfirefox