生成器和迭代器

window.onload=function () {
let arr=[1,2,3,4,5,6,7,4];
function *fn(arr) {
for(let i=0;i<arr.length;i++){
yield arr[i];
}
}
let result=fn(arr); //
console.log(result); //fn {<suspended>}
let result2=result.next(); //迭代
console.log(result2); // {value: 1, done: false}done: false value: 1__proto__: Object
console.log(result2.value); //1
result2=result.next(); // 迭代 但是fn并不会重置 停留在上一个调用位置
result2=result.next(); // 继续测试
console.log(result2.value); //3
}
//总结:函数名前面加*号代表是生成器 返回内容前加yield 在调用后赋值迭代才会会返回后接表达式值 并在该位置停留 等待下次迭代

原文地址:https://www.cnblogs.com/threeyou/p/13442787.html