“Getting NaN on reduce() method” 可以翻译为 “在reduce()方法上得到NaN”。

huangapple go评论84阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年8月5日 03:53:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定