ES6: for...of VS for...in
阿新 • • 發佈:2017-09-12
highlight 範圍 ons dom erro 原型 設計 tor 數字
for...of和for...in是js中常用的兩個遍歷的方法,但是它們遍歷是有區別的,最主要的區別就是:
(1)for...of是遍歷key, value中的value即鍵值,for...of一般是forEach的替代方法。
for...in是遍歷key, value中的key即鍵名,而key一般就是索引index的作用,所以記憶的話in可以對應index,for...in是遍歷index的,這樣可以很容易區分出for..of和for..in。
(2)for...of循環可以使用的範圍包括數組、Set和Map結構、某些類似數組的對象(比如arguments對象、DOM NodeList對象)、Generator對象,以及字符串。
(3)for...of是ES6提供的方法,for...in是js原生的方法
(4) for..of不能遍歷普通對象而for..in能遍歷普通對象
var es6 = { edition: 6, committee: "TC39", standard: "ECMA-262" }; for (e in es6) { console.log(e); } // edition // committee // standard for (e of es6) { console.log(e); } // TypeError: es6 is not iterable
(5)for...in和for...of遍歷過程中可以用break,return,其他的遍歷方法不能用這兩個關鍵字
var es6 = { edition: 6, committee: "TC39", standard: "ECMA-262" }; for (e in es6) { if(e == ‘committee‘) { break; } else { console.log(e); } } //edition var arr1 = [1,2,3,4]; for(value of arr1){ if(value == 3) { break; }else{ console.log(value) } } // 1 // 2
(6)for...in循環有幾個缺點
- 數組的鍵名是數字,但是for...in循環是以字符串作為鍵名“0”、“1”、“2”等等。
- for...in循環不僅遍歷數字鍵名,還會遍歷手動添加的其他鍵,甚至包括原型鏈上的鍵。
- 某些情況下,for...in循環會以任意順序遍歷鍵名。
總之,for...in循環主要是為遍歷對象而設計的,不適用於遍歷數組。
(7)for...of的優點
- 有著同for...in一樣的簡潔語法,但是沒有for...in那些缺點。
- 不同用於forEach方法,它可以與break、continue和return配合使用。
- 提供了遍歷所有數據結構的統一操作接口。
ES6: for...of VS for...in