1. 程式人生 > 其它 >圖解Array的forEach、map、find、reducer、filter方法

圖解Array的forEach、map、find、reducer、filter方法


JavaScript 陣列 Array.prototype 提供了幾個非常方便的迭代方法,這裡用圖解的方式來理解這些方法。

Array.forEach

forEach() 方法對陣列的每個元素執行一次提供的函式。

var array1 = ["a", "b", "c"];

array1.forEach(function (element) {
  console.log(element);
});

// expected output: "a"
// expected output: "b"
// expected output: "c"

Array.map

map() 方法建立一個新陣列,其結果是該陣列中的每個元素都呼叫一個提供的函式後返回的結果。

var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map((x) => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Array.filter

filter() 方法建立一個新陣列, 其包含通過所提供函式實現的測試的所有元素。

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];

const result = words.filter((word) => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

Array.find

find() 方法返回陣列中滿足提供的測試函式的第一個元素的值。否則返回 undefined。

var array1 = [5, 6, 8, 130, 44];

var found = array1.find(function (element) {
  return element > 10;
});

console.log(found);
// expected output: 130

Array.reduce

reduce() 方法對陣列中的每個元素執行一個由您提供的 reducer 函式(升序執行),將其結果彙總為單個返回值。

const array1 = [1, 2, 3, 4];
const reducer = (acc, cur) => acc + cur;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15