You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node电商购物车calculateTotal函数计算总价返回NaN问题排查

问题原因
  • 核心错误出在for循环的变量使用逻辑:你在循环头部将j赋值为items.length(即数值3),后续所有读取商品sku、单价、购买数量的操作,都错误地直接对j(数字类型)取值,数字不存在这些属性,读取结果为undefined,undefined参与算术运算后结果自然为NaN。
  • 单品折扣判断逻辑也存在错误:原代码用discount.itemNum == j.sku判断,应该和当前遍历到的商品sku比对,而非和长度变量j比对,且原单品折扣分支未叠加商品本身的应付金额,只做了折扣扣减,逻辑存在遗漏。
修正后代码
const calculateTotal = (items, discount) => {
  let total = 0;
  let discountAmt = 0;

  console.log(discount);
  console.log(items);
  console.log(items.length);

  for (let i = 0; i < items.length; i++) {
    // 取当前遍历到的商品项
    const currentItem = items[i];
    discountAmt = 0;

    if (discount.type == "Item" && discount.itemNum == currentItem.sku) {
      discountAmt = currentItem.price * currentItem.qty * (discount.percent / 100);
      total = total + (currentItem.price * currentItem.qty) - discountAmt;
    } else {
      total = total + currentItem.price * currentItem.qty;
    }
  }

  if (discount.type == "Order") {
    discountAmt = total * (discount.percent / 100);
    total = total - discountAmt;
  }

  console.log(total);

  return total;
};
验证结果

用你提供的入参调用修正后的函数,返回结果为71.95,计算逻辑:(10.992)+(16.992)+15.99 = 21.98 + 33.98 + 15.99 = 71.95,和预期一致。

内容的提问来源于stack exchange,提问作者Andrew Vargas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 08:15:07