[轉] 簡述js中 for in 與 for of 區別

for in是ES5標準,遍歷key. 
for of是ES6標準,遍歷value.javascript

for (var key in arr){ console.log(arr[key]); } for (var value of arr){ console.log(value); }

 

一個比較神奇的例子:java

Object.prototype.objCustom = function () {}; Array.prototype.arrCustom = function () {}; let iterable = [3, 5, 7]; iterable.foo = "hello"; for (let i in iterable) { console.log(i); // 0, 1, 2, "foo", "arrCustom", "objCustom" } for (let i of iterable) { console.log(i); // 3, 5, 7
相關文章
相關標籤/搜索