在不显式更改的情况下,reduce 方法中的累加器值如何更改?
How does the accumulator value in reduce method change without explicitly changing it?
第一次写到这里,请见谅
我很确定我对 reduce() 方法有很好的掌握,但我似乎无法特别理解一个概念。在这个特定问题中,我们被要求找到所有数组参数共享的元素。我能够使用 reduce 方法构建一个答案。我知道它有效,而且我知道有更有效的解决方案,但我似乎无法理解累加器值如何自我修改,即使我没有重新分配它的值。
让我解释一下:在当前值(即第二个数组)的第一次迭代之后,我检查当前元素是否与我的累加器(第一个数组)共享共性。在检查并将公共值推入结果后,results = [5, 15, 7]
。下一次迭代开始时的累加器值也成为我的结果值集,但同样,我没有明确地重新分配累加器值,例如使用 acc = results
。累加器如何在没有明确更改的情况下“理解”更改?我有点接受了这种机制,但希望得到解释。如果我应该提供更多说明,请告诉我。谢谢!
function intersection(arrays) {
return arrays.reduce((acc, curr) => {
// here, acc = the first array --> 5, 15, 7 --> 15, 5
let results = []
for(let element of curr) {
if(acc.includes(element)) results.push(element)
}
// here, results = 5, 15, 7 --> 15, 5 --> 15, 5
return results
})
}
const arr1 = [5, 10, 15, 20, 7, 3];
const arr2 = [15, 88, 1, 5, 7, 21];
const arr3 = [1, 10, 15, 5, 20, 21];
console.log(intersection([arr1, arr2, arr3]));
// should log: [5, 15]
看到这个基本版本的 reduce,您可能会更好地理解它,它在调用时简单地对数组值求和
Array.prototype.myReduce = function(callback, start) {
// inital value of acc is start value `0` set in call
let acc = start;
this.forEach((elem, i) => {
// acc gets assigned the return value from the callback
// every iteration of this internal loop
acc = callback(acc, elem, i, this)
});
// then finally gets returned from the outer function
return acc
};
const arr = [1, 2, 3]
const res = arr.myReduce((a, c, i, arr) => {
return a + c // returned to `acc` in the forEach loop above
}, 0)
console.log('Result:', res) // expect 1+2+3 = 6
第一次写到这里,请见谅
我很确定我对 reduce() 方法有很好的掌握,但我似乎无法特别理解一个概念。在这个特定问题中,我们被要求找到所有数组参数共享的元素。我能够使用 reduce 方法构建一个答案。我知道它有效,而且我知道有更有效的解决方案,但我似乎无法理解累加器值如何自我修改,即使我没有重新分配它的值。
让我解释一下:在当前值(即第二个数组)的第一次迭代之后,我检查当前元素是否与我的累加器(第一个数组)共享共性。在检查并将公共值推入结果后,results = [5, 15, 7]
。下一次迭代开始时的累加器值也成为我的结果值集,但同样,我没有明确地重新分配累加器值,例如使用 acc = results
。累加器如何在没有明确更改的情况下“理解”更改?我有点接受了这种机制,但希望得到解释。如果我应该提供更多说明,请告诉我。谢谢!
function intersection(arrays) {
return arrays.reduce((acc, curr) => {
// here, acc = the first array --> 5, 15, 7 --> 15, 5
let results = []
for(let element of curr) {
if(acc.includes(element)) results.push(element)
}
// here, results = 5, 15, 7 --> 15, 5 --> 15, 5
return results
})
}
const arr1 = [5, 10, 15, 20, 7, 3];
const arr2 = [15, 88, 1, 5, 7, 21];
const arr3 = [1, 10, 15, 5, 20, 21];
console.log(intersection([arr1, arr2, arr3]));
// should log: [5, 15]
看到这个基本版本的 reduce,您可能会更好地理解它,它在调用时简单地对数组值求和
Array.prototype.myReduce = function(callback, start) {
// inital value of acc is start value `0` set in call
let acc = start;
this.forEach((elem, i) => {
// acc gets assigned the return value from the callback
// every iteration of this internal loop
acc = callback(acc, elem, i, this)
});
// then finally gets returned from the outer function
return acc
};
const arr = [1, 2, 3]
const res = arr.myReduce((a, c, i, arr) => {
return a + c // returned to `acc` in the forEach loop above
}, 0)
console.log('Result:', res) // expect 1+2+3 = 6