TypeScript foreach返回

Ros*_*oss 7 javascript c# typescript

C#开发人员在这里.试着做一些TypeScript.只是偶然发现了一些奇怪的行为.然而,考虑它更有意义,我想知道是否有一种更好的方法可以做到这一点 - 看起来像返回foreach并不会返回包含foreach循环的函数,这可能是C#开发人员的期望.

只是想知道是否有更简洁的方法:

example() {
    var forEachReturned;

    this.items.forEach(item => {
        if (true) {
            forEachReturned = true;
            return;
        }
    });

    if (forEachReturned) {
        return;
    }

    // Do stuff in case forEach has not returned
}
Run Code Online (Sandbox Code Playgroud)

谢谢大家!

JLR*_*she 15

更清洁的方法是不使用.forEach.如果您使用TypeScript,几乎不需要它:

example() {
    for (let item of this.items) {
        if (true) {
            return;
        }
    }      

    // Do stuff in case forEach has not returned
}
Run Code Online (Sandbox Code Playgroud)

如果循环中的代码没有任何副作用,并且您只是检查每个项目的条件,您还可以使用以下函数方法.some:

example() {
    if (this.items.some(item => item === 3)) {
        return;
    }

    // Do stuff in case we have not returned
}
Run Code Online (Sandbox Code Playgroud)

  • @Ross我能想到发生这种情况的唯一情况是在稀疏数组的情况下,例如“let arr = [1,2,3,,,4,5,6]”。`forEach` 和其他数组原型方法(`map`、`filter`)将跳过空条目,但 `for..of` 不会。 (3认同)