javascript Map(),Reduce()和Filter()

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Map(),Reduce()和Filter()相关的知识,希望对你有一定的参考价值。

// All three avoids mutation of the original array

// Map()
const arr = [1, 2, 3, 4];
// takes in the value, the index, and the array itself
const arrTimesTwo = arr.map((value, index, arr) => {
  return value * 2;
});

// Filter()
// Filter receives the same arguments as map()
// The only difference is the callback needs to return either true or false
const names = ["chase", "john", "jacob", "diego"];
const newNames = names.filter(name => {
  return name.includes('a');
});

// Reduce()
// Takes an array and reduces it to a single value
// It differs in callback arguments
// The callback receives the accumulator (accumulates all returned values)
// It's value is the accumulation of the previous returned accumulations
const numbers = [1, 2, 3, 4, 5];
const final = numbers.reduce((acc, currValue, currIndex, array) => {
  console.log(acc, currValue);
  return acc + currValue;
},0) // this 0 here is optional. You are telling what value to start with

以上是关于javascript Map(),Reduce()和Filter()的主要内容,如果未能解决你的问题,请参考以下文章

javascript reduce map函数方法

javascript Map(),Reduce()和Filter()

javascript 处理数组[each,map,reduce]

如何形象地解释 JavaScript 中 map,foreach,reduce 间的区别

JavaScript基础——高阶函数(map and reduce)

JavaScript:使用 reduce() 和 map() 简化数组导致未定义