1、使用 Array.prototype.some() 方法代替
some() 方法會在找到第一個符合條件的元素時停止循環(huán)。
例如:
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)時停止循環(huán)。
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)時停止循環(huán)。
請注意,該方法找到的元素不會返回,需要在回調(diào)中自己處理。
3、使用 for循環(huán)代替
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)時停止循環(huán)。
4、使用 try-catch 結(jié)構(gòu)
可以在 forEach 循環(huán)內(nèi)部使用 throw 語句來中斷循環(huán),并在外部使用 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)時停止循環(huán)。
請注意,使用 throw 語句中斷 forEach 循環(huán)可能會使代碼變得更加復(fù)雜,并且容易出現(xiàn)錯誤。因此,如果可能的話,應(yīng)該使用前面提到的 Array.prototype.some() 或 for 循環(huán)來代替。
5、使用自定義的迭代器函數(shù)
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)時停止循環(huán)。
這種方法雖然不夠簡潔,但是它可以在不改變原來的forEach函數(shù)的情況下,增加新的功能。
6、使用 Array.prototype.find() 或 Array.prototype.findIndex() 方法代替
find() 方法會在找到符合條件的第一個元素后返回該元素,并停止循環(huán)。
例如:
let array = [1, 2, 3, 4, 5];
let found = array.find(function(element) {
return element === 3;
});
console.log(found);
上述代碼會在找到第一個符合條件的元素(即 3)時停止循環(huán)并返回該元素。
Array.prototype.findIndex() 方法會在找到符合條件的第一個元素后返回該元素的索引,并停止循環(huán)。
例如:
let array = [1, 2, 3, 4, 5];
let index = array.findIndex(function(element) {
return element === 3;
});
console.log(index);
上述代碼會在找到第一個符合條件的元素(即 3)時停止循環(huán)并返回該元素的索引。
使用 Array.prototype.find() 或 Array.prototype.findIndex() 方法可以在 forEach 循環(huán)中找到符合條件的第一個元素并停止循環(huán)。這兩種方法是在找到符合條件的元素后返回該元素或索引,而不是像 some() 方法或 for 循環(huán)中需要再次返回一個布爾值或使用 throw 語句來中斷循環(huán)。文章來源:http://www.zghlxwxcb.cn/news/detail-633335.html
總之,主要方法還是通過其它方式代替 forEach 循環(huán)的中斷,只有方法4 使用 try-catch 結(jié)構(gòu)是實際意義上中斷 forEach 循環(huán)。文章來源地址http://www.zghlxwxcb.cn/news/detail-633335.html
到了這里,關(guān)于js中斷 forEach 循環(huán)的幾種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!