# JavaScript生成器

P.S. 迭代器生成器： function*定义的东西叫迭代器的生成器（简称生成器），因为调用它返回一个迭代器

2.生成无限序列

3.方便遍历

2.高级用法 function* fib() {var a = 1;var b = 1;while (true) {var current = b;b = a;a = a + current;var reset = yield current;if (reset) {a = 1;b = 1;}}}var fibSeq = fib();fibSeq.next();// => Object {value: 1, done: false}fibSeq.next();// => Object {value: 1, done: false}fibSeq.next();// => Object {value: 2, done: false}fibSeq.next();// => Object {value: 3, done: false}fibSeq.next();// => Object {value: 5, done: false}fibSeq.next(false);// => Object {value: 8, done: false}fibSeq.next(true);// => Object {value: 1, done: false}fibSeq.next(false);// => Object {value: 1, done: false}fibSeq.next(false);// => Object {value: 2, done: false}

next()可以接受参数，此参数会被当做yield的返回值传回函数，这样就可以控制函数内部的状态，例如上面的是否reset

3.比较绕的例子 function* fun(a) {a = yield a + 1;a = yield a * 2;yield a * 2 + 1;}var iter = fun(3);iter.next(0);// => Object {value: 4, done: false}iter.next(0);// => Object {value: 0, done: false}iter.next(1);// => Object {value: 3, done: false}类似的：function* fun(a) {a = yield a = a + 1;a = yield a = a * 2;yield a = a * 2 + 1;}var iter = fun(3);iter.next(0);// => Object {value: 4, done: false}iter.next(0);// => Object {value: 0, done: false}iter.next(1);// => Object {value: 3, done: false}

4.其它

function* fun() {yield 1;yield 2;}var iter = fun();var newIter = (for (i of iter) i * 2);newIter.next();// => Object { value: 2, done: false }newIter.next();// => Object { value: 4, done: false }

FF支持这种语法，Chrome不支持

for…of用来遍历属性值，for…in用来遍历属性名，forEach是Array.prototype上的方法，能同时遍历属性名和属性值

var arr = [3, 5, 7];arr.foo = "hello";for (var i in arr) {console.log(i); // logs "0", "1", "2", "foo"}for (var i of arr) {console.log(i); // logs "3", "5", "7"}let arr = [3, 5, 7];arr.foo = "hello";arr.forEach(function (element, index) { console.log(element); // logs "3", "5", "7" console.log(index);// logs "0", "1", "2"}); 2.yield*

function* g1() { yield 2; yield 3; yield 4;}function* g2() { yield 1; yield* g1(); yield 5;}var iterator = g2();console.log(iterator.next()); // { value: 1, done: false }console.log(iterator.next()); // { value: 2, done: false }console.log(iterator.next()); // { value: 3, done: false }console.log(iterator.next()); // { value: 4, done: false }console.log(iterator.next()); // { value: 5, done: false }console.log(iterator.next()); // { value: undefined, done: true }