【发布时间】:2017-12-06 03:06:25
【问题描述】:
有人可以帮我理解这里发生了什么吗?
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);
程序因“acc.push 不是函数”而崩溃
检查第一个记录的accumulator 表明我们有 push 方法 - 这是一个真正的功能:
【问题讨论】:
-
return acc.concat(item); -
push是否返回推送的元素?尝试推入单独的行,然后返回 acc。
标签: javascript arrays ecmascript-6 reduce