
在React开发中,使用forEach循环对数值进行累加求和时,可能会遇到NaN(Not a Number)的问题。本文旨在解决此类问题,并提供正确的代码示例,确保数值计算的准确性。
当使用forEach循环累加数值时,如果没有正确初始化累加变量,JavaScript会将其默认为undefined。undefined与任何数值进行加法运算都会得到NaN。因此,在循环开始前,务必为累加变量赋一个初始值,通常为0。
以下是一个修复后的代码示例,展示了如何正确初始化累加变量:
const productsObj = [{
id: 1,
name: 'Sweater',
size: 'M',
gender: 'Men',
price: 2300,
printPrice: 180,
minQuantity: 1,
total: 2300,
},
{
id: 2,
name: 'Shirt',
size: 'M',
materijal: 'Pamuk',
gender: 'Men',
price: 1500,
printPrice: 180,
minQuantity: 1,
total: 1500,
}];
const [products, setProducts] = React.useState(productsObj);
//onChange on quantity input:
const handleQuantityChange = (e, id) => {
setProducts(
products.map((item) => {
if (item.id === id) {
const quantity = parseInt(e.target.value, 10); // 确保是数字类型
const newTotal = item.price * quantity;
return {
...item,
quantity: quantity,
total: newTotal,
};
} else {
return item;
}
})
);
};
//function that sums all the total's
const allTotal = () => {
let sum = 0; // 初始化累加变量为0
products.forEach((e) => {
sum += e.total;
});
return sum;
};关键修改:
除了forEach循环,还可以使用reduce方法更简洁地实现数组元素的累加:
const allTotal = () => {
return products.reduce((sum, product) => sum + product.total, 0);
};reduce方法接受两个参数:一个回调函数和一个初始值。回调函数接收两个参数:累加器(sum)和当前元素(product)。初始值(0)作为第一次调用回调函数时的累加器值。
在React中使用forEach或reduce进行数值累加时,务必注意初始化累加变量,并确保参与计算的数据类型正确。正确处理这些细节可以避免NaN错误,保证数值计算的准确性。使用reduce方法通常可以使代码更简洁易读。
以上就是React中求和运算返回NaN的解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号