nan,同时计算数组上的总值Map

kxkpmulp  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(262)

每次Map数组时,我都试图计算一个值,但我得到了(5)个nan。如果我在中硬编码一个值,我会得到我要查找的正确值。看起来问题与值的Map有关。如果我输入console.log每个值,我会得到正确的数字。

console.log(calculateTotalReviews(16, 40)); returns: (5)40
   console.log(review.valueCount); returns: 16, 8, 6, 13,
   console.log(review.starRating); returns: 5, 4, 3, 2, 1
{customerReviews.map(review => (
            <CustomerRatingBar review={review} />
        ))}
const customerTotalReviewsData = {
  totalNoOfReviews: 50,
  averageRating: 4.8,
};

const customerReviews = [{
    starRating: 5,
    valueCount: 16,
  },
  {
    starRating: 4,
    valueCount: 8,
  },
  {
    starRating: 3,
    valueCount: 6,
  },
  {
    starRating: 2,
    valueCount: 13,
  },
  {
    starRating: 1,
    valueCount: 7,
  },
];

const calculateTotalReviews = (amountOfCustomers, totalReviews) =>
  (amountOfCustomers / totalReviews) * 100;

console.log(calculateTotalReviews(review.valueCount, review.totalNoOfReviews)) // Returning (5)NaN
6ljaweal

6ljaweal1#

我只能假设,其中一个值 review.valueCountreview.totalNoOfReviewsundefined ,这将使计算返回 NaN .
看看你的变量,你想用它吗 review.valueCountcustomerTotalReviewsData.totalNoOfReviews (而不是 review.totalNoOfReviews )?

calculateTotalReviews(review.valueCount, customerTotalReviewsData.totalNoOfReviews)
qpgpyjmq

qpgpyjmq2#

review.totalnoofreviews是 undefined . 对其进行的计算将导致 NaN .
您可能希望将代码更改为:

{customerReviews.map(review => (
            <CustomerRatingBar review={review} totalNo={customerTotalReviewsData.totalNoOfReviews}/>
        ))}
console.log(calculateTotalReviews(review.valueCount, totalNo))

相关问题