我听说过JavaScript中的“yield”关键字,但我发现关于它的文档非常糟糕。有人能给我解释一下(或者推荐一个解释它的网站)它的用法和用途吗?
当前回答
给出一个完整的答案:yield的工作原理类似于return,但在发电机中。
对于通常给出的例子,其工作原理如下:
function *squareGen(x) {
var i;
for (i = 0; i < x; i++) {
yield i*i;
}
}
var gen = squareGen(3);
console.log(gen.next().value); // prints 0
console.log(gen.next().value); // prints 1
console.log(gen.next().value); // prints 4
但是yield关键字还有第二个用途。它可以用来向生成器发送值。
为了澄清,举个小例子:
function *sendStuff() {
y = yield (0);
yield y*y;
}
var gen = sendStuff();
console.log(gen.next().value); // prints 0
console.log(gen.next(2).value); // prints 4
它的工作原理是,将值2赋给y,在它停止在第一个yield(返回0)后将其发送给生成器。
这使我们能够看到一些非常时髦的东西。(查协程)
其他回答
在学习yield之前,您需要了解生成器。生成器是使用函数*语法创建的。Generator函数不执行代码,而是返回一种称为Generator的迭代器。当使用下一个方法给出一个值时,生成器函数将继续执行,直到遇到yield关键字。使用yield返回一个包含两个值的对象,一个是value,另一个是done(布尔值)。该值可以是数组、对象等。
不要忘记使用非常有用的“x of generator”语法来遍历生成器。根本不需要使用next()函数。
function* square(x){
for(i=0;i<100;i++){
x = x * 2;
yield x;
}
}
var gen = square(2);
for(x of gen){
console.log(x);
}
使用yield关键字的斐波那契序列生成器。
function* fibonacci() {
var a = -1, b = 1, c;
while(1) {
c = a + b;
a = b;
b = c;
yield c;
}
}
var fibonacciGenerator = fibonacci();
fibonacciGenerator.next().value; // 0
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 2
它用于迭代器生成器。基本上,它允许您使用过程代码制作(可能是无限的)序列。请参阅Mozilla的文档。
在我看来,MDN文档非常好。
The function containing the yield keyword is a generator. When you call it, its formal parameters are bound to actual arguments, but its body isn't actually evaluated. Instead, a generator-iterator is returned. Each call to the generator-iterator's next() method performs another pass through the iterative algorithm. Each step's value is the value specified by the yield keyword. Think of yield as the generator-iterator version of return, indicating the boundary between each iteration of the algorithm. Each time you call next(), the generator code resumes from the statement following the yield.
推荐文章
- 将lodash导入到angular + typescript应用程序中
- 什么时候使用setAttribute vs .attribute=在JavaScript?
- 每60秒调用一个函数
- 我如何上传一个文件与JS获取API?
- 在JavaScript中是否有一个“not in”操作符来检查对象属性?
- 我如何能得到滚动条的位置与JavaScript?
- JavaScript中的yield关键字是什么?
- 如何显示一个对象的所有方法?
- .js和.mjs文件有什么区别?
- Axios处理错误
- ESLint解析错误:意外的令牌
- 同时映射和过滤一个数组
- TypeScript:创建一个空的类型容器数组
- 在JavaScript中将大字符串分割为n大小的块
- 如何从JavaScript字符串中剥离HTML标签?