reduce()方法不会使用object数组返回正确的结果

问题描述 投票:0回答:1

我有以下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.你能告诉我我做错了什么,为什么?

javascript ecmascript-6 reduce
1个回答
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,而不是object,所以它没有属性votes,这就是为什么NaN

© www.soinside.com 2019 - 2024. All rights reserved.