使用 ES6 生成器,我看到这样的代码:
var trivialGenerator = function *(array) {
var i,item;
for(var i=0; i < array.length; i++){
item = array[i];
yield item;
};
};
是否可以编写类似于下面代码的内容?
var trivialGenerator = function *(array) {
array.forEach(function *(item){
yield item;
});
};
不,你不能使用yield https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield内部函数内部。但就你的情况而言,你不需要它。您可以随时使用for-of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of循环而不是forEach https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach方法。它看起来会更漂亮,你可以使用continue https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue, break https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break, yield https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield在里面:
var trivialGenerator = function *(array) {
for (var item of array) {
// some item manipulation
yield item;
}
}
您可以使用for-of
如果您对其中的项目进行一些操作。否则你绝对不需要创建这个生成器,因为array
has iterator界面 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol原生地。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)