在 JavaScript 中,遍歷數組有多種方法,下面介紹幾種經典方法。
for 循環
用 for 循環遍歷數組是最基礎、最原始的方法。
const arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
forEach()
forEach() 是 ES5 中新增的方法,用來遍歷數組,可以傳遞一個函數作爲參數,這個函數會被依次作用到數組的每一個元素上。
const arr = [1, 2, 3, 4, 5];
arr.forEach(function(item) {
console.log(item);
});
forEach() 方法的參數是一個函數,該函數可以接受三個參數:數組元素的值,元素的索引和數組本身。
const arr = [1, 2, 3];
arr.forEach(function(value, index, array) {
console.log(value, index, array);
});
map()
map() 方法也是 ES5 中新增的方法,可以遍歷數組並執行一個回調函數,它會返回一個新數組,該數組由回調函數的返回值組成。
const arr = [1, 2, 3];
const mappedArr = arr.map(function(item) {
return item * 2;
});
console.log(mappedArr); // [2, 4, 6]
for…of 循環
ES6 引入了 for…of 循環,可以簡潔地遍歷數組。
const arr = [1, 2, 3, 4, 5];
for (const item of arr) {
console.log(item);
}
需要注意的是,for…of 循環不能遍歷對象,只能遍歷數組、Set、Map、字符串等可迭代對象。
總結:以上是比較常見的幾種 JavaScript 遍歷數組的方法。不論使用哪種方法,都要注意循環的性能和效率。在使用 forEach() 或 map() 方法時,需要注意不可修改數組內的元素值。如果需要修改元素值,可以使用 for 循環或 for…of 循環。