[1,2,3].forEach(function(el) {
    if(el === 1) break;
});

如何在JavaScript中使用新的forEach方法实现这一点?我尝试过返回;,return false;和断裂。break崩溃,return只会继续迭代。


当前回答

如果您想保持forEach语法,这是一种保持其高效的方法(尽管不如常规for循环好)。立即检查一个变量,该变量是否知道您是否想要脱离循环。

此示例使用匿名函数来围绕forEach创建函数范围,您需要存储已完成的信息。

(函数(){var element=document.getElementById('打印结果');var done=假;[1,2,3,4].forEach(功能(项目){如果(完成){return;}var text=document.createTextNode(项);element.appendChild(文本);如果(项==2){done=真;回来}});})();<div id=“printed result”></div>

我的两分钱。

其他回答

在其他网站上找到此解决方案。您可以在try/catch场景中包装forEach。

if(typeof StopIteration == "undefined") {
 StopIteration = new Error("StopIteration");
}

try {
  [1,2,3].forEach(function(el){
    alert(el);
    if(el === 1) throw StopIteration;
  });
} catch(error) { if(error != StopIteration) throw error; }

此处提供更多详细信息:http://dean.edwards.name/weblog/2006/07/enum/

您可以创建forEach的变体,该变体允许break、continue、return甚至async/await:(用TypeScript编写的示例)

export type LoopControlOp = "break" | "continue" | ["return", any];
export type LoopFunc<T> = (value: T, index: number, array: T[])=>LoopControlOp;

Array.prototype.ForEach = function ForEach<T>(this: T[], func: LoopFunc<T>) {
    for (let i = 0; i < this.length; i++) {
        const controlOp = func(this[i], i, this);
        if (controlOp == "break") break;
        if (controlOp == "continue") continue;
        if (controlOp instanceof Array) return controlOp[1];
    }
};

// this variant lets you use async/await in the loop-func, with the loop "awaiting" for each entry
Array.prototype.ForEachAsync = async function ForEachAsync<T>(this: T[], func: LoopFunc<T>) {
    for (let i = 0; i < this.length; i++) {
        const controlOp = await func(this[i], i, this);
        if (controlOp == "break") break;
        if (controlOp == "continue") continue;
        if (controlOp instanceof Array) return controlOp[1];
    }
};

用法:

function GetCoffee() {
    const cancelReason = peopleOnStreet.ForEach((person, index)=> {
        if (index == 0) return "continue";
        if (person.type == "friend") return "break";
        if (person.type == "boss") return ["return", "nevermind"];
    });
    if (cancelReason) console.log("Coffee canceled because: " + cancelReason);
}

不幸的是,在这种情况下,如果不使用forEach会更好。而是使用一个常规的for循环,它现在将完全按照您的预期工作。

var array = [1, 2, 3];
for (var i = 0; i < array.length; i++) {
  if (array[i] === 1){
    break;
  }
}

这不是最有效的,因为你仍然循环所有元素,但我认为这可能值得考虑非常简单的:

let keepGoing = true;
things.forEach( (thing) => {
  if (noMore) keepGoing = false;
  if (keepGoing) {
     // do things with thing
  }
});

如果您想保持forEach语法,这是一种保持其高效的方法(尽管不如常规for循环好)。立即检查一个变量,该变量是否知道您是否想要脱离循环。

此示例使用匿名函数来围绕forEach创建函数范围,您需要存储已完成的信息。

(函数(){var element=document.getElementById('打印结果');var done=假;[1,2,3,4].forEach(功能(项目){如果(完成){return;}var text=document.createTextNode(项);element.appendChild(文本);如果(项==2){done=真;回来}});})();<div id=“printed result”></div>

我的两分钱。