我有以下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.你能告诉我我做错了什么,为什么?
调用你的函数传递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
,在第二次,accumulator
是int
,而不是object
,所以它没有属性votes
,这就是为什么NaN