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

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


当前回答

简短回答:用于。。。为此中断或更改代码以避免中断forEach。不要使用.some()或.every()来模拟。。。打破重写代码以避免。。。中断循环,或用于。。。打破每次你使用这些方法。。。上帝杀死了小猫。

长答案:

.some()和.every()都返回布尔值,如果有任何元素的传递函数返回true,.some(返回true,如果有元素的传递的函数返回false,则every返回false。这就是函数的含义。使用函数来实现它们并不意味着什么,这比使用表来布局而不是CSS要糟糕得多,因为这会让所有阅读代码的人感到沮丧。

此外,使用这些方法的唯一可能方法是。。。break替代方法是产生副作用(在.some()回调函数之外更改一些vars),这与for。。。打破

因此,使用.some()或.every()作为。。。断环替代方案并没有副作用,这对。。。打破,这是令人沮丧的,所以这不是更好的。

您可以随时重写代码,这样就不需要。。。打破您可以使用.filter()过滤数组,也可以使用.slice()等拆分数组,然后使用.forEach()或.map()处理该部分数组。

其他回答

您可以创建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);
}

没有内置的功能可以为Each进行破解。要中断执行,必须抛出某种异常。

var BreakException={};尝试{[1,2,3]对于每个(函数(el){控制台日志(el);如果(el==2)抛出BreakException;});}捕获(e){如果(e!==BreakException)抛出e;}

JavaScript异常并不漂亮。如果你真的需要打破传统的for循环,那么它可能更合适。

使用数组#some

而是使用Array#some:

[1,2,3]一些(函数(el){控制台日志(el);返回el==2;});

这之所以有效,是因为只要按数组顺序执行的任何回调返回true,就会立即返回true,从而缩短其余回调的执行。

有些,它的逆every(返回false时停止)和forEach都是ECMAScript第五版方法,需要在缺少它们的浏览器上添加到Array.prototype中。

使用数组#间隔

[1,2,3]每(v=>{如果(v>2){return false//“break”}控制台日志(v);return true//如果不中断,则必须返回true});

考虑使用jquery的each方法,因为它允许在回调函数中返回false:

$.each(function(e, i) { 
   if (i % 2) return false;
   console.log(e)
})

Lodash库还提供了takeWhile方法,可以与map/reduce/fold等链接:

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']

// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['barney']

// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']

// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []

如果迭代后不需要访问数组,可以通过将数组的长度设置为0来退出。如果您在迭代后仍然需要它,可以使用slice来克隆它。。

[1,3,4,5,6,7,8,244,3,5,2].forEach(function (item, index, arr) {
  if (index === 3) arr.length = 0;
});

或者使用克隆:

var x = [1,3,4,5,6,7,8,244,3,5,2];

x.slice().forEach(function (item, index, arr) {
  if (index === 3) arr.length = 0;
});

这是一个比在代码中抛出随机错误更好的解决方案。

我为此使用了nullhack,它试图访问null的属性,这是一个错误:

try {
  [1,2,3,4,5]
  .forEach(
    function ( val, idx, arr ) {
      if ( val == 3 ) null.NULLBREAK;
    }
  );
} catch (e) {
  // e <=> TypeError: null has no properties
}
//