JavaScript使用reduce计算数组购物车总价时出现NaN问题求助
问题修复方案
错误点梳理
- 属性名不匹配:自定义
PRODUCTO类存储价格的属性是precio,但reduce逻辑里错误读取不存在的VALUEcprecio属性,同时初始数组第一个元素是数字0,也没有该属性,直接导致NaN - reduce使用错误:reduce第一个参数回调的第一个形参是累加器(上一轮计算的结果),不是数组元素,原逻辑把累加器当成数组元素读取属性完全不符合API规范
- 执行顺序错误:先计算总和再把新商品插入数组,导致刚新增的商品价格没有被计入本次总和
- 类型错误:input输入的价格是字符串类型,没有转为数字,后续计算会出现字符串拼接或者转换失败的NaN问题
修正后代码
JS部分
// 初始为空数组,不需要预置0 let array = []; function adddata() { let cproducto = document.getElementById("producto"); let cprecio = document.getElementById("precio"); // 输入值转数字,避免字符串计算异常 let VALUEcprecio = Number(cprecio.value); // 先将新增商品推入数组,再计算总和 let objeto = new PRODUCTO(cproducto.value, VALUEcprecio) array.push(objeto); let table = document.getElementById("dymanictable"); let rowCount = table.rows.length; let row = table.insertRow(rowCount); row.insertCell(0).innerHTML = cproducto.value; row.insertCell(1).innerHTML = cprecio.value; // 正确配置reduce:设置初始累加值为0,遍历取每个商品的precio属性累加 const VALORtotal = array.reduce((a, b) => a + b.precio, 0); row.insertCell(2).innerHTML = VALORtotal; // 原有调试日志可保留 console.log(objeto) console.log(array); console.log(VALORtotal) } class PRODUCTO { constructor(producto, precio) { this.producto = producto, this.precio = precio; } }
HTML部分无需改动,保留原有代码即可正常运行
内容的提问来源于stack exchange,提问作者belu irina
相关产品推荐
相关产品推荐

