咱們不同:for...of與for...in

定義

二者都是遍歷的方法,最早能想到的區別是,前者是遍歷鍵名,後者是遍歷鍵值。
看一下二者的定義:javascript

  • for...in 遍歷當前對象的全部可枚舉屬性(包括自有屬性,從原型繼承的屬性),遍歷順序是無序的
  • for...of 遍歷當前可遍歷(iterable)數據結構擁有的可迭代元素(iterator),是有序的,是ES6提供的新方法

那麼iterator是什麼呢java

遍歷器 iterator

iterator是一種接口,爲不一樣的數據結構提供統一的訪問機制。
iterator主要供for...of消費。
一種數據結構只要部署了iterator接口,就稱之爲可遍歷的。
ES6中提供了一些具有原生iterator接口的數據結構(包括Array、Map、Set、String、TypedArray、函數的arguments對象、NodeList對象。不包括Object),部署在數據結構的Symbol.iterator屬性中。
因此也能夠說,一種數據結構只要有Symbol.iterator屬性,就稱之爲可遍歷的。es6

var myIterable = {};
myIterable[Symbol.iterator] = function* () {
    yield 1;
    yield 2;
    yield 3;
};

for (let value of myIterable) { 
    console.log(value); 
}
// 1
// 2
// 3

for...of使用示例

// 遍歷數組
let iterable = [10, 20, 30];
for (let value of iterable) {
  value += 1;
  console.log(value);
}
// 11
// 21
// 31

// 遍歷字符串
let iterable = 'boo';

for (let value of iterable) {
  console.log(value);
}
// "b"
// "o"
// "o"

// 遍歷Map
let iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let entry of iterable) {
  console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]
for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3

// 遍歷arguments
(function() {
  for (let argument of arguments) {
    console.log(argument);
  }
})(1, 2, 3);
// 1
// 2
// 3

若是用中斷for...of,能夠使用break、continue、throw或return數組

function* foo(){ 
  yield 1; 
  yield 2; 
  yield 3; 
}; 

for (let o of foo()) { 
  console.log(o); 
  break; // 終止iterator,跳出循環
}

for...in使用示例

// 從原型繼承的屬性
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 in iterable) {
  if (iterable.hasOwnProperty(i)) {
    console.log(i); // 0, 1, 2, "foo"
  }
}

for (let i of iterable) {
  console.log(i); // 3, 5, 7
}

參考

ECMAScript 6 入門 - Iterator 和 for...of 循環
developer.mozilla.org - Difference between for...of and for...in數據結構

相關文章
相關標籤/搜索