AIo*_*Ion 15 javascript arrays reduce ecmascript-6
有人可以帮我理解这里发生的事情吗?
let firstArray = [];
firstArray.push(1);
firstArray.push(1);
firstArray.push(1);
console.log("firstArray", firstArray); // result [ 1, 1, 1 ] - as expected.
let secondArray = [1, 2, 3].reduce((acc, item) => {
console.log("acc", acc);
console.log("typeof acc", typeof acc);
// on first passing, the accumulator (acc) is Array[] == object.
// on the second passing the acc == number.
// but why?
/// i expect to get [1,1,1] as my secondArray.
return acc.push(1);
}, []);
console.log("secondArray", secondArray);
Run Code Online (Sandbox Code Playgroud)
程序崩溃"acc.push不是一个函数"
并检查accumulator我们有push方法的第一个记录的节目 - 这是一个真正的功能:
Ori*_*ori 32
返回值Array#push是推送后数组的新长度.这意味着在第二次迭代中acc是一个数字,它没有push方法.
修复很简单 - 将push和return语句分开:
const secondArray = [1, 2, 3].reduce((acc, item) => {
acc.push(1);
return acc;
}, []);
console.log(secondArray);Run Code Online (Sandbox Code Playgroud)