如何从数组上的隐式循环中断(类似于break
语句)?
Array.prototype.forEach
等函数隐含了对数组元素的循环。我想有条件地提前中断这个循环。
这是一个人为的例子:
const colours = ["red", "orange", "yellow", "green", "blue", "violet"];
colours.map(item => {
if (item.startsWith("y")) {
console.log("The yessiest colour!");
break;
}
});
导致SyntaxError: Illegal break statement
。
如何像break
语句一样中断循环?
发布于 2018-05-28 11:32:48
Array#map
、Array#forEach
等从来都不是被设计成可以停止的。这感觉很奇怪,因为map
的意图也是forEach
实际上是迭代所有项。
此外,我不认为通知调用者发生了break
事件是可能的,因为它位于一个不是原始循环的组成部分的函数中。
因此,让我们看看一个自定义方法,它在第一次出现true
时停止循环,而不返回匹配值本身:
Object.defineProperty(Array.prototype, 'untilTrue', {
enumerable: false,
value: function(lambda) {
for(let i in this) {
if(lambda.call(this, this[i])) return;
}
}
});
const colours = ["red", "orange", "yellow", "green", "blue", "violet"];
colours.untilTrue(item => {
if (item.startsWith("y")) {
console.log("The yessiest colour!");
return true;
}
console.log(item);
});
将此自定义untilTrue
与Array#find
的使用进行比较
const colours = ["red", "orange", "yellow", "green", "blue", "violet"];
colours.find(item => {
if (item.startsWith("y")) {
console.log("The yessiest colour!");
return true;
}
return false;
});
唯一值得注意的区别是untilTrue
不返回匹配项-除了调用lambda
之外,Array#find
还会返回匹配项。
因此,通常我会坚持使用Array#find
来保持代码的整洁,并像这样使用它:
const colours = ["red", "orange", "yellow", "green", "blue", "violet"];
if(colours.find(item => item.startsWith("y")) !== undefined) {
console.log("The yessiest colour!");
}
这会在第一次匹配时停止循环(并返回匹配的元素)。另请注意,您必须与undefined
进行比较-如果您正在搜索false
或null
值,如果只是与true
进行比较,则检查永远不会评估为true
。
发布于 2018-05-28 10:45:24
你不能用常规的方法来做这件事。您可以通过记住循环是否“中断”来模拟break
行为。缺少这种解决方案的是循环实际上继续(尽管跳过了迭代逻辑)。
let isBroken = false;
colours.map(item => {
if (isBroken) {
return;
}
if (item.startsWith("y")) {
console.log("The yessiest colour!");
isBroken = true;
return;
}
});
对于您的示例,最好的解决方案是使用普通的for
循环。
for (colour of colours) {
if (colour.startsWith("y")) {
console.log("The yessiest colour!");
break;
}
}
此外,您还可以使用一种肮脏的方式来实际停止map
循环。
colours.map((item, index, array) => {
if (item.startsWith("y")) {
console.log("The yessiest colour!");
array.splice(0, index);
}
});
// The colours array will be modified after this loop
发布于 2018-05-28 11:08:02
如果您唯一的选择是使用Array.forEach,则可以抛出异常
请参阅以下内容:
How to short circuit Array.forEach like calling break?
还有其他的方法也可以解决你的问题。例如,如果您想检查某个条件并根据该条件中断循环,则可以使用method: Array.prototype.some()。
示例可以在这里参考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
https://stackoverflow.com/questions/50558227
复制相似问题