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