generator生成器iterator遍历器和yield

时间:2021-05-02 23:31:07

generator方法()返回一个iterator

使用generator时永远先去调用generator()方法

for of对iterator的调用过程(babel参照)

1,_iterator.next() 每次循环 调用iterator的next()
2,var v = _step.value;将next().value赋值给当前项
babel地址

var arr=[1,2];
for(let v of arr){
console.log(v)
}
"use strict";

var arr = [1, 2];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
for (var _iterator = arr[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var v = _step.value;

console.log(v);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}

yield* 后跟generator(生成器嵌套)

function * g1(){
yield 'a'
yield 'b'
}
function * g2(){
yield 1
yield* g1()
yield 2
}
for(let v of g2()){
console.log(v)
}

generator生成器iterator遍历器和yield