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 回圈,
作者:yuzhihui出處:http://www.cnblogs.com/yuzhihui/ 宣告:歡迎任何形式的轉載,但請務必注明出處!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/542335.html
標籤:JavaScript
上一篇:Vue 中如何監測陣列的變化?
