// 使用 foreach 时,由于它不会返回任何值(即总是返回 undefined),所以不能直接使用 break 语句退出循环。
// 如果需要提前退出循环,可以考虑使用 for 循环或者数组的 some 方法。
// 示例代码:使用 some 方法实现提前退出循环
const array = [1, 2, 3, 4, 5];
array.some(function(item) {
console.log(item);
if (item === 3) {
return true; // 提前退出循环
}
return false;
});
// 输出:
// 1
// 2
// 3
// 如果你坚持使用 foreach,那么你需要用一个外部变量来控制是否继续执行:
let shouldExit = false;
array.forEach(function(item) {
if (shouldExit) return;
console.log(item);
if (item === 3) {
shouldExit = true;
}
});
// 输出:
// 1
// 2
// 3
上一篇:js websocket框架
下一篇:js foreach用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站