JavaScript中有多種遍歷數(shù)組的方法,每種方法都有其特點(diǎn)和適用場(chǎng)景。以下是幾種常見的遍歷數(shù)組的方法及其區(qū)別:
- for循環(huán):是最基本的遍歷數(shù)組的方法,適用于任何情況。但代碼不夠簡(jiǎn)潔,支持提前跳出循環(huán)。break跳出循環(huán),continue跳出當(dāng)前分支繼續(xù)下一個(gè)循環(huán)。
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
- for...of循環(huán):是ES6新增的遍歷語法,適用于遍歷可迭代對(duì)象(如數(shù)組、字符串、Map等)。語法簡(jiǎn)潔,但無法獲取索引。支持提前跳出循環(huán)。
let arr = [1, 2, 3, 4, 5];
for (let value of arr) {
console.log(value);
}
- forEach方法:也是數(shù)組提供的方法之一,會(huì)依次處理數(shù)組中的每個(gè)元素,但無法跳出循環(huán)。同時(shí),無法獲取當(dāng)前元素的索引??梢允褂胷eturn的方式跳出當(dāng)前循環(huán)分支.不支持break和continue
let arr = [1, 2, 3, 4, 5];
arr.forEach(value => {
if (value === 2) {
return;
}
console.log(value);
});
// 打印
1
3
4
5
- map方法:會(huì)返回一個(gè)新的數(shù)組,原始數(shù)組不變。主要用于對(duì)數(shù)組中的每個(gè)元素進(jìn)行操作并返回處理后的新數(shù)組。可以跳出循環(huán),但會(huì)生成新的數(shù)組。不支持break和continue
let arr = [1, 2, 3, 4, 5];
let newArr = arr.map(value => {
if (value % 2 === 0) { // 只處理偶數(shù),相當(dāng)于跳出循環(huán)
return value;
}
});
console.log(newArr); // [2, 4]
- filter方法:會(huì)返回一個(gè)新的數(shù)組,只包含符合條件的元素。與map方法類似,可以跳出循環(huán),但會(huì)生成新的數(shù)組。不支持break和continue
let arr = [1, 2, 3, 4, 5];
let newArr = arr.filter(value => {
if (value % 2 === 0) { // 只保留偶數(shù),相當(dāng)于跳出循環(huán)
return true;
}
});
console.log(newArr); // [2, 4]
- for...in循環(huán):用于遍歷對(duì)象的屬性或數(shù)組的索引。但通常不用于遍歷數(shù)組元素,因?yàn)闀?huì)遍歷到原型鏈上的屬性。且無法跳出循環(huán)。
- for...of循環(huán)與for...in循環(huán)的區(qū)別:for...in循環(huán)會(huì)遍歷對(duì)象所有可枚舉的屬性(包括原型鏈上的),而for...of循環(huán)只會(huì)遍歷對(duì)象自身的可枚舉屬性(不包括原型鏈上的)。因此,for...of循環(huán)更適合遍歷數(shù)組或類數(shù)組對(duì)象。