[1,2,3].forEach(function(el) {
if(el === 1) break;
});
如何在JavaScript中使用新的forEach方法实现这一点?我尝试过返回;,return false;和断裂。break崩溃,return只会继续迭代。
[1,2,3].forEach(function(el) {
if(el === 1) break;
});
如何在JavaScript中使用新的forEach方法实现这一点?我尝试过返回;,return false;和断裂。break崩溃,return只会继续迭代。
当前回答
您可以创建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);
}
其他回答
还有一种方法:
var wageType = types.filter(function(element){
if(e.params.data.text == element.name){
return element;
}
});
console.dir(wageType);
现在,在ECMAScript2015(也称为ES6)中使用新的for of循环有更好的方法来实现这一点。例如,此代码不打印数字5之后的数组元素:
常量arr=[0,1,2,3,4,5,6,7,8,9,10];for(arr常量){控制台日志(el);如果(el==5){打破}}
从文档中:
两者都用于。。。为。。。of语句对某些内容进行迭代。它们之间的主要区别在于迭代的内容。用于。。。in语句按原始插入顺序迭代对象的可枚举财产。用于。。。of语句迭代可迭代对象定义要迭代的数据。
迭代中需要索引吗?可以使用Array.entries():
for (const [index, el] of arr.entries()) {
if ( index === 5 ) break;
}
同意@bobince,支持。
此外,仅供参考:
Prototype.js有这样的功能:
<script type="text/javascript">
$$('a').each(function(el, idx) {
if ( /* break condition */ ) throw $break;
// do something
});
</script>
$break将由Prototype.js在内部捕获和处理,打破“each”循环,但不会产生外部错误。
有关详细信息,请参见Prototype.JS API。
jQuery也有一种方法,只需在处理程序中返回false,即可尽早中断循环:
<script type="text/javascript">
jQuery('a').each( function(idx) {
if ( /* break condition */ ) return false;
// do something
});
</script>
有关详细信息,请参见jQuery API。
您可以使用每种方法:
[1,2,3].every(function(el) {
return !(el === 1);
});
ES6
[1,2,3].every( el => el !== 1 )
对于旧浏览器支持使用:
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
更多详情请点击此处。
如果迭代后不需要访问数组,可以通过将数组的长度设置为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;
});
这是一个比在代码中抛出随机错误更好的解决方案。