js停止循环代码是什么(JavaScript 中断 forEach 循环)
1 、使用 Array.prototype.some() 方法代替
some() 方法会在找到第一个符合条件的元素时停止循环 。
例如:
let array = [1, 2, 3, 4, 5]; array.some(function(element, index, array) { if (element === 3) { console.log("Found 3 at index " + index); return true; } });上述代码会在找到第一个符合条件的元素(即 3)时停止循环 。
2 、使用 Array.prototype.every() 方法代替
let array = [1, 2, 3, 4, 5]; let stop = array.every(function(element) { console.log(element); if (element === 3) { console.log("Found 3 at index "); return false; } return true; });上述代码会在找到第一个符合条件的元素(即 3)时停止循环。
请注意 ,该方法找到的元素不会返回 ,需要在回调中自己处理 。
3、使用 for循环代替
let array = [1, 2, 3, 4, 5]; for(let i = 0; i < array.length; i++) { if (array[i] === 3) { console.log("Found 3 at index " + i); break; } }上述代码也会在找到第一个符合条件的元素(即 3)时停止循环 。
4 、使用 try-catch 结构
可以在 forEach 循环内部使用 throw 语句来中断循环,并在外部使用 catch 语句来捕获该异常 。
例如:
let array = [1, 2, 3, 4, 5]; try { array.forEach(function(element, index, array) { if (element === 3) { console.log("Found 3 at index " + index); throw "StopIteration"; } }); } catch (e) { if (e !== "StopIteration") throw e; }上述代码会在找到第一个符合条件的元素(即 3)时停止循环 。
请注意 ,使用 throw 语句中断 forEach 循环可能会使代码变得更加复杂 ,并且容易出现错误 。因此 ,如果可能的话 ,应该使用前面提到的 Array.prototype.some() 或 for 循环来代替 。
5 、使用自定义的迭代器函数
let array = [1, 2, 3, 4, 5]; function forEach(array, callback) { for (let i = 0; i < array.length; i++) { callback(array[i], i, array); if (array[i] === 3) { console.log("Found 3 at index " + i); break; } } } forEach(array, function(element, index, array) { console.log(element); });上述代码会在找到第一个符合条件的元素(即 3)时停止循环 。
这种方法虽然不够简洁 ,但是它可以在不改变原来的forEach函数的情况下 ,增加新的功能 。
6 、使用 Array.prototype.find() 或 Array.prototype.findIndex() 方法代替
find() 方法会在找到符合条件的第一个元素后返回该元素 ,并停止循环 。
例如:
let array = [1, 2, 3, 4, 5]; let found = array.find(function(element) { return element === 3; }); console.log(found);上述代码会在找到第一个符合条件的元素(即 3)时停止循环并返回该元素。
Array.prototype.findIndex() 方法会在找到符合条件的第一个元素后返回该元素的索引 ,并停止循环 。
例如:
let array = [1, 2, 3, 4, 5]; let index = array.findIndex(function(element) { return element === 3; }); console.log(index);上述代码会在找到第一个符合条件的元素(即 3)时停止循环并返回该元素的索引 。
使用 Array.prototype.find() 或 Array.prototype.findIndex() 方法可以在 forEach 循环中找到符合条件的第一个元素并停止循环。这两种方法是在找到符合条件的元素后返回该元素或索引 ,而不是像 some() 方法或 for 循环中需要再次返回一个布尔值或使用 throw 语句来中断循环 。
总之,主要方法还是通过其它方式代替 forEach 循环的中断 ,只有方法4 使用 try-catch 结构是实际意义上中断 forEach 循环 。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!