我可以从内部函数中屈服吗? [英] Can I yield from an inner function?

查看:118
本文介绍了我可以从内部函数中屈服吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ES6生成器,我看到如下代码:

With ES6 generators, I see code like this:

var trivialGenerator = function *(array) {
    var i,item;
    for(var i=0; i < array.length; i++){
        item = array[i];
        yield item;
    };
};

是否可以编写更像下面代码的内容?

Is it possible to write something more like the code below instead?

var trivialGenerator = function *(array) {
    array.forEach(function *(item){
        yield item;
    });
};

我问,因为的经典循环是一种憎恶。

I'm asking because the classic for loop is an abomination.

推荐答案

不,你不能使用 yield 。但在你的情况下,你不需要它。您始终可以使用 for-of 循环而不是 forEach 方法。它看起来会更漂亮,你可以使用 继续 中断 yield 里面:

No, you can't use yield inside of the inner function. But in your case you don't need it. You can always use for-of loop instead of forEach method. It will look much prettier, and you can use continue, break, yield inside it:

var trivialGenerator = function *(array) {
    for (var item of array) {
        // some item manipulation
        yield item;
    }
}

您可以使用代表 - 如果您对其中的项目进行了一些操作。否则你绝对不需要创建这个生成器,因为 array iterator interface 本地。

You can use for-of if you have some manipulations with item inside it. Otherwise you absolutely don't need to create this generator, as array has iterator interface natively.

这篇关于我可以从内部函数中屈服吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆