reduce() map()

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 }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容