xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js generator function All In One

js generator function All In One

function* & yield*

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

const gf = generator(10);

console.log(gf.next().value);
// 10
console.log(gf.next().value);
// 20

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.

Generator 对象由生成器函数返回,它同时符合可迭代协议迭代器协议

function* generator() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = generator();
// Generator Object

console.log(gen.next().value);
// 1
console.log(gen.next().value); 
// 2
console.log(gen.next().value); 
// 3

// 等价于 IIFE
const gen = function* generator() {
  yield 1;
  yield 2;
  yield 3;
}();

gen.next().value;
// 1
gen.next().value;
// 2
gen.next().value;
// 3
gen.next().value;
// undefined

// 等价于 IIFE & `yield*`
const gen = function* generator() {
  yield* [1, 2, 3];
}();

gen.next().value;
// 1
gen.next().value;
// 2
gen.next().value;
// 3
gen.next().value;
// undefined

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator

GeneratorFunction

const GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction

demos

Uint8ClampedArray & ArrayBuffer & TypedArray

// from an iterable 
const iterable = function* (){
  // generator function
  yield* [1,2,3]; 
}();

const ui8ca = new Uint8ClampedArray(iterable);

// from an iterable 
function* gen(){
  // generator function
  yield* [1,2,3]; 
}

// 等价于
const iterable = gen();
const ui8ca = new Uint8ClampedArray(iterable);

refs

https://www.cnblogs.com/xgqfrms/p/16161925.html



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-04-18 20:24  xgqfrms  阅读(41)  评论(0编辑  收藏  举报