请问有人能帮我理解这里发生了什么吗?
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方法 - 它是一个真正的函数:
item
添加到acc
数组末尾并返回新的数组。 - fubarpush
方法会返回被推入的元素吗?请尝试将push
操作和返回操作分开写在不同的行中。 - Carcigenicate