英文:
Getting NaN on reduce() method
问题
I am working with ReactJS. I have a JSON Object like this:
[
{
"id": "1",
"category": "cellphones",
"name": "Xiaomi Redmi Note 10",
"stock": "99",
"price": "100",
"quantity": "3"
},
{
"id": "2",
"category": "cellphones",
"name": "Iphone 11",
"stock": "3",
"price": "1000",
"quantity": "5"
},
{
"id": "3",
"category": "laptops",
"name": "MSI GF65 Thin",
"stock": "40",
"price": "2000",
"quantity": "2"
}
]
And I want to get the overall total of these items by doing something like this:
const getAllTotal = () => {
const sum = cartItems.reduce(
(prev, next) => prev.quantity * prev.price + next.quantity * next.price,
0
);
console.log(sum);
return sum;
};
The thing is, every time I call that function, the console returns NaN.
I first thought it was caused by the type of the keys, so I tried to enclose said keys into the parseInt() method, but it returned the same NaN. What am I doing wrong?
英文:
I am working with ReactJS. I have a JSON Object like this:
[
{
"id": "1",
"category": "cellphones",
"name": "Xiaomi Redmi Note 10",
"stock": "99",
"price": "100",
"quantity": "3"
},
{
"id": "2",
"category": "cellphones",
"name": "Iphone 11",
"stock": "3",
"price": "1000",
"quantity": "5"
},
{
"id": "3",
"category": "laptops",
"name": "MSI GF65 Thin",
"stock": "40",
"price": "2000",
"quantity": "2"
}
]
And i want to get the overall total of this items by doing something like this:
const getAllTotal = () => {
const sum = cartItems.reduce(
(prev, next) => prev.quantity * prev.price + next.quantity * next.price,
0
);
console.log(sum);
return sum;
};
The thing is, everytime i call that function, the console returns NaN.
I first thought it was caused by the type of the keys, so i tried to enclose said keys into the parseInt() method, but it returned the same NaN. What am i doing wrong?
答案1
得分: 4
我认为你没有正确使用array.reduce()方法。这是正确的形式,请尝试:
const getAllTotal = () => {
const sum = cartItems.reduce(
(prev, next) => prev + next.quantity * next.price,
0
);
console.log(sum);
return sum;
};
查看此链接以获取array.reduce()方法的正确实现。
英文:
I think you are not using array.reduce() method properly. Here is the correct form try this:
const getAllTotal = () => {
const sum = cartItems.reduce(
(prev, next) => prev + next.quantity * next.price,
0
);
console.log(sum);
return sum;
};
Take a look at this link for proper implementation of array.reduce() method
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论