ES6生成器:.next()的输入值
ES6 Generators: input value for .next()
我关注这个很棒的博客,这里有一个生成器发送.next()
方法值的简单示例:
var answers = [
`It is certain`, `It is decidedly so`, `Without a doubt`,
`Yes definitely`, `You may rely on it`, `As I see it, yes`,
`Most likely`, `Outlook good`, `Yes`, `Signs point to yes`,
`Reply hazy try again`, `Ask again later`, `Better not tell you now`,
`Cannot predict now`, `Concentrate and ask again`,
`Don't count on it`, `My reply is no`, `My sources say no`,
`Outlook not so good`, `Very doubtful`
]
function answer () {
return answers[Math.floor(Math.random() * answers.length)]
}
// The most relevant part
function* chat () {
while (true) {
let question = yield '[Genie] ' + answer()
console.log(question)
}
}
我真的不明白这个输入将如何产生这个输出:
var g = chat()
g.next()
console.log(g.next('[Me] Will ES6 die a painful death?').value)
// <- '[Me] Will ES6 die a painful death?'
// <- '[Genie] My sources say no'
第一个输出来自哪里——结果的[Me]部分?
yield
之后的表达式将熄灭(返回)。传递给next()
的值进入,yield
表达式计算为该值。请注意,在第一个.next()调用中传递的任何值都会被丢弃而不使用。
-
g.next()
被称为let question = yield '[Genie] ' + answer() ^-------------------^ execution is paused here, this expression is evaluated and the result will go out(returned) {value:"[Genie] ...",done:false}
-
则
g.next('[Me] Will ES6 die a painful death?')
称为g.next('[Me] Will ES6 die a painful death?').value ^----------------------------------^ string goes in, execution continues, yield expression will be evaluated as the passed in string let question = yield '[Genie] ' + answer(); //becomes -v let question = '[Me] Will ES6 die a painful death?';
-
question
等于[Me]
字符串 question
通过console.log(question)
登录到控制台-
继续执行,直到遇到下一个产量
let question = yield '[Genie] ' + answer() ^-------------------^ execution is paused here, this expression is evaluated and the result will go out(returned) {value:"[Genie] ...",done:false}
-
现在
g.next('[Me] Will ES6 die a painful death?')
评估为{value:"[Genie] ...",done:false}
最后一行评估如下:
console.log( g.next('[Me] Will ES6 die a painful death?').value ); //becomes console.log( ({value:"[Genie] ...",done:false}).value ); //which becomes console.log("[Genie] ...");
让我消除了很多困惑的是关于收益的MDN文档。
语法
[rv] = yield [expression];
rv
返回传递给生成器的next()方法以继续执行的可选值。
这就是为什么对next
的第二次调用将决定let question
的值。这就是我们继续执行的地方。
生成器然后打印出问题,继续下一轮循环,得出下一个精灵的答案并停止。如果还有另一个对next
的调用,则传递给它的参数将确定let question
的下一个值。
相关文章:
- 为什么不't Javascript对我的输入值进行了一些重新检查
- 可以't让我的if语句处理js中的html表单输入
- 名称输入的索引
- 如何编写HTML输入的JS内联
- 要求输入在数据列表中
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 让文本输入幻灯片显示输入时的新文本输入?然后向后滑动
- 如何将输入(type=text)从html表单传递到javascript函数
- 单击jquery清除输入值
- 而循环只设置php中输入字段中的第一个值
- 在输入字段中将最小金额设置为
- jQuery自定义验证比较多个输入的序列
- Sails.js:同时发布文本输入和一个文件
- 使用javascript检查多个输入值,并在1次检查中标记多个输入框
- 如何在输入字段中的按钮的帮助下打开日历,该字段的类型为“=”;日期”;
- ES6生成器:.next()的输入值
- 使用jquery UI next按钮提交输入字段值,php将返回结果
- 在使用next()填充时显示下一个输入字段
- 仅当最后一个 AJAX 请求在 JavaScript 中完成时,才输入 next 进行迭代
- 如何检测“enter”键在输入中按下“next”键;在ie8 -10中使用JavaScript的行为