簡單實用,JavaScript 的 8 個數組遍歷方法
引言
在 JavaScript 中,有一些用于遍歷數組的方法。經常的總結并記住它們,可以讓我們的工作得心應手。
map
map() 數組的每個元素都會調用回調函數,并將處理結果返回一個新數組。
- const numbers = [1, 2, 3, 4];
- const foo = number => number + 10;
- const newNumbers = numbers.map(foo);
- console.log(`新數組:${newNumbers}`);
- console.log(`舊數組:${numbers}`);
- /*
- * 新數組:11,12,13,14
- * 舊數組:1,2,3,4
- */
every
every() 方法使用指定函數檢測數組中的所有元素是否滿足條件,元素全部滿足條件,方法返回 true ,有一個元素不滿足條件,方法返回 false 且其余元素不再檢測。
- const numbers = [1,2,3,4];
- const foo = num => num < 5;
- if (numbers.every(foo)) {
- console.log('數組中所有元素都小于 5'); // is ok
- } else {
- console.log('數組中至少有一個元素大于 5');
- }
some
some() 方法使用指定函數檢測數組中是否有元素滿足條件,有一個元素滿足條件,方法返回 true 且剩余的元素不會再執行檢測,沒有滿足條件的元素,方法返回 false 。
- const numbers = [1,2,3,4];
- const foo = num => num > 3;
- if (numbers.some(foo)) {
- console.log('數組中至少有一個元素值大于 3'); // is ok
- } else {
- console.log('數組中沒有大于 3 的元素值');
- }
filter
filter() 方法通過一個函數,篩選數組中的元素。用符合條件的元素創建一個新數組。
- const numbers = [1,2,3,4];
- const foo = number => number > 2;
- const newNumbers = numbers.filter(foo);
- console.log(`原始數組 [${numbers}] 中,滿足 > 2 的元素有 : ${newNumbers}`);
- // 原始數組 [1,2,3,4] 中,滿足 > 2 的元素有 : 3,4
reduce
reduce() 方法接收一個函數累加器,數組中的每個元素 (從左到右) 應用于函數,最終計算出一個最終值。
- const numbers = [1, 2, 3, 4];
- const sum = (total, num) => total + num;
- const numbers_sum = numbers.reduce(sum, 0); // 將 0 作為 reduce 的初始值
- console.log(`原始數組 '${numbers}' 的元素累加后,最終值是 ${numbers_sum}`);
- // 原始數組 [1,2,3,4] 的元素累加后,最終值是 10
reduceRight() 和 reduce() 使用方法一樣,區別是它從右到左將數組中的每個元素應用于函數。
for
傳統的 for 循環遍歷數組很常用。
- const numbers = [1, 2, 3, 4];
- for (let index = 0; index < numbers.length; index++) {
- console.log(numbers[index]); // 1 2 3 4
- }
forEach
forEach() 將數組的每個元素傳入回調函數,且對空數組不會執行回調函數。
- const numbers = [1, 2, 3, 4];
- numbers.forEach((number, index, numbers) => {
- console.log(`下標 ${index} 在數組 ${numbers} 中的值是 ${number}`);
- });
- /*
- * 下標 0 在數組 1,2,3,4 中的值是 1
- * 下標 1 在數組 1,2,3,4 中的值是 2
- * 下標 2 在數組 1,2,3,4 中的值是 3
- * 下標 3 在數組 1,2,3,4 中的值是 4
- */
while
while 也可以遍歷數組,但很少用。
- let index = 0;
- const numbers = [1,2,3,4];
- while(index < numbers.length) {
- console.log(numbers[index]);
- index ++;
- }
- // 1 2 3 4