JavaScript – Iterator(JavaScript – Iterator)

前言

es6 以后经常可以看到 for…of 的踪迹. 如果你细看会发现它挺神奇的. 不只是 Array 可以被 for of, 有些对象也可以被 for of.

const array = [1, 2, 3];
console.log(Array.isArray(array)); // true
for (const value of array) {
  console.log(value); // 1, 2, 3
}

上面 Array 能·被 for of, make sense.

下面 isArray 是 false, querySelectorAll 返回的是一个 NodeListOf 对象. 但是依然可以被 for of.

const notArray = document.querySelectorAll('h1');
console.log(Array.isArray(notArray)); // false
for (const value of notArray) {
  console.log(value); // h1
}

其原因是, 只要是 Iterable 对象就可以被 for of 遍历. 而 Array 和 NodeListOf 都属于 Iterable 对象, 自然就可以被 for of 遍历了.

————————

preface

After ES6, you can often see for The trace of If you look closely, you will find it very magical Not only can array be used for of, but some objects can also be used for of

const array = [1, 2, 3];
console.log(Array.isArray(array)); // true
for (const value of array) {
  console.log(value); // 1, 2, 3
}

上面 Array 能·被 for of, make sense.

The following isarray is false, and queryselectorall returns a nodelistof object But it can still be used for of

const notArray = document.querySelectorAll('h1');
console.log(Array.isArray(notArray)); // false
for (const value of notArray) {
  console.log(value); // h1
}

The reason is that as long as it is an iteratable object, it can be traversed by for of Array and nodelistof belong to Iterable objects, which can be traversed by for of naturally