美文网首页
reduce() map()

reduce() map()

作者: 愤的小鸟怒 | 来源:发表于2019-08-07 17:33 被阅读0次

map()

map() 方法返回一个新数组(不会改变原始数组),数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。

reduce

(一) array.reduce(callback, initialValue) :

  1. callback(accumulator, currentValue, currentIndex,array)
  2. initialValue、

注:

  1. 如果传入了 initialValue,accumulator 的初始值就等于 initialValue,currentValue 的值等于 array 的第一个值, 如果没有传入 initialValue,accumulator 初始值就等于 array 的第一个值,而 currentValue 就会跳过第一个值,等于 array 的第二个值。

  2. reduce 最终返回的值是最后一次调用 callback 函数返回的值,也就是数组中数字和初始值的总和。

(二) 例子:

1 实现一个累加器。

const nums = [1, 23, 34, 12];
const sum = nums.reduce((rcc, item) => rcc += item,0);
console.log(sum);

2 计算数组内数字重复的个数,对于字符串同样有效。

const nums = [3, 5, 6, 82, 1, 4, 3, 5, 82];

const result = nums.reduce((tally, amt) => {
    tally[amt] ? tally[amt]++ : tally[amt] = 1;
    return tally;
}, {});

console.log(result);
//{ '1': 1, '3': 2, '4': 1, '5': 2, '6': 1, '82': 2 }

相关文章

网友评论

      本文标题:reduce() map()

      本文链接:https://www.haomeiwen.com/subject/ucdadctx.html