# JavaScript 迭代器与生成器

## 1、什么是迭代器：

function makeIterator(array){
var nextIndex = 0;

return {
next: function(){
return nextIndex < array.length ?
{value: array[nextIndex++], done: false} :
{done: true};
}
};
}

var it = makeIterator(['yo', 'ya']);

console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done);  // true


## 2、可迭代协议

function makeIterator(){
var nextIndex = 0;
var array= [1,2,4,5,6,7,8,9,10]
return {
next: function(){
return nextIndex < array.length ?
{value: array[nextIndex++], done: false} :
{done: true};
}
};
}
var s = {a:1,b:2,c:3};//对象不是可迭代对象
s[Symbol.iterator]=makeIterator;//实现Symbol.iterator 方法
for (var x of s){
console.log(x)
}
//可以使用迭代for of 循环
1 debugger eval code:2:1
2 debugger eval code:2:1
4 debugger eval code:2:1
5 debugger eval code:2:1
6 debugger eval code:2:1
7 debugger eval code:2:1
8 debugger eval code:2:1
9 debugger eval code:2:1
10


## 3、默认的可迭代对象

###### 字符串是可迭代对象
for ( var i of 'string'){
console.log(i)
}
s debugger eval code:2:1
t debugger eval code:2:1
r debugger eval code:2:1
i debugger eval code:2:1
n debugger eval code:2:1
g

var s = ('string')[Symbol.iterator]()
s  // String Iterator {  } //返回的s是迭代器对象
[...s]  //对象展开符 Array(6) [ "s", "t", "r", "i", "n", "g" ]

###### 数组、map、 set 都是可迭代的对象
var ss = ([1,2,3,4,5])[Symbol.iterator]()
//undefined
ss
//Array Iterator {  }


## 4、生成器

function* generator(i) {
yield i;
yield i + 10;
}

var gen = generator(10);

console.log(gen.next().value);
// expected output: 10

console.log(gen.next().value);
// expected output: 20


###### next方法传参：

function *gen(){
yield 10;
y=yield 'foo';
yield y;
}

var gen_obj=gen();
console.log(gen_obj.next());// 执行 yield 10，返回 10
console.log(gen_obj.next());// 执行 yield 'foo'，返回 'foo'
console.log(gen_obj.next(10));// 将 10 赋给上一条 yield 'foo' 的左值，即执行 y=10，返回 10
console.log(gen_obj.next());// 执行完毕，value 为 undefined，done 为 true

###### yield*
function* anotherGenerator(i) {
yield i + 1;
yield i + 2;
yield i + 3;
}

function* generator(i){
yield i;
yield* anotherGenerator(i);// 移交执行权
yield i + 10;
}

var gen = generator(10);

console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20

posted @ 2022-03-28 09:43  恩恩先生  阅读(173)  评论(0编辑  收藏  举报