reduce()方法无法使用对象数组

时间:2018-08-08 21:23:13

标签: javascript ecmascript-6 reduce

我有以下js代码:

 const choiseArray=[
    {choice: "Shooter",url:"/questions/10/choices/01",votes:3},
    {choice: "Shooter2",url:"/questions/10/choices/02",votes:2},
    {choice: "Shooter3",url:"/questions/10/choices/03",votes:4},
    {choice: "Shooter3",url:"/questions/10/choices/03",votes:11},
];
const reducer = (accumulator, currentValue) => parseInt(accumulator.votes) + parseInt(currentValue.votes);

const totalVotes= choiseArray.reduce(reducer);

console.info(totalVotes);

我想使用reduce来获得总票数,但是始终我会收到NaN而不是20的结果。 你能告诉我我在做什么错,为什么吗?

1 个答案:

答案 0 :(得分:3)

调用传递0作为reduce第二个参数的函数,这将是累加器,然后在函数中将值求和,而不访问accumulator.votes

const choiseArray=[
    {choice: "Shooter",url:"/questions/10/choices/01",votes:3},
    {choice: "Shooter2",url:"/questions/10/choices/02",votes:2},
    {choice: "Shooter3",url:"/questions/10/choices/03",votes:4},
    {choice: "Shooter3",url:"/questions/10/choices/03",votes:11},
];
const reducer = (accumulator, currentValue) => accumulator + parseInt(currentValue.votes);

const totalVotes= choiseArray.reduce(reducer, 0);

console.info(totalVotes);

您当前的问题是,在第一次迭代中,您有accumulator.votes + currentValue.votes,在第二次迭代中,accumulatorint,而不是{{1 }},因此它没有属性object,这就是votes

的原因