我有一个任务,我找到了一个完美的解决方案,虽然我真的不明白它是如何工作的。任何人都可以帮我详细解释一下吗?特别是这一个(countsMap, item) => countsMap.set(item, countsMap.get(item) + 1 || 1)
var testArray = ["dog", "dog", "cat", "buffalo", "wolf", "cat", "tiger", "cat"];
function compressArray(original) {
return array.reduce((countsMap, item) => countsMap.set(item, countsMap.get(item) + 1 || 1), new Map());
}
console.log(compressArray(testArray));
答案 0 :(得分:0)
reduce()方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 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
对于名为箭头功能的=>
,它就像
(param1, param2, …, paramN) => { statements }
var materials = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium'];
console.log(materials.map((material) => {
return material.length;
})); // [8, 6, 7, 9]
答案 1 :(得分:0)
让我们把它分解成组成部分
const arr = [1, 2, 3]; // some array
const sum = (accumilator, nextValue) => accumilator + nextValue; // some function
// n.b. the return value is the next accumilator
const initialValue = 0;
const result = arr.reduce(sum, initialValue); // 6, i.e. 1 + 2 + 3
我发现向某人表达这一点的最简单方法是用手写它
// lets start the same as before
const arr = [1, 2, 3];
const sum = (accumilator, nextValue) => accumilator + nextValue;
// now to calculate the result,
let accumilator = 0; // = initial value
for (let i = 0; i < arr.length; ++i) {
const nextValue = arr[i];
accumilator = sum(accumilator, nextValue);
}
accumilator; // 6
那么这看起来像是手写的,例如在for循环?
{{1}}
答案 2 :(得分:0)