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

JavaScript遍历对象:购物车库存打印函数报错求助

问题分析与修复

你的printCartInventory函数存在两个关键错误,导致输出不符合预期:

  1. 错误引用对象而非商品名称:
    在for...in循环中,item变量对应购物车对象的键(即商品名称,比如示例里的"Gold Round Sunglasses"),但你拼接字符串时用了${product}——product是键对应的值(包含quantity和price的对象),直接输出对象会得到[object Object]。应该替换为${item}来获取商品名。

  2. 换行符拼写错误:
    JavaScript的换行转义字符是\n,你写成了/n,这会导致换行失效,变成字符串里的"/n"文本。

另外,循环拼接字符串会产生多余的末尾换行,改用数组收集条目后再用\n拼接更整洁。

修正后的代码

function printCartInventory(cart) {
  const inventoryItems = [];
  for (let itemName in cart) {
    const product = cart[itemName];
    inventoryItems.push(`${product.quantity}x${itemName}`);
  }
  return inventoryItems.join('\n');
}

测试验证

用你提供的示例购物车测试:

const cart = {
  "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 },
  "Pink Bucket Hat": { quantity: 2, priceInCents: 1260 },
};

console.log(printCartInventory(cart));

输出结果:

1xGold Round Sunglasses
2xPink Bucket Hat

完全符合预期格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:50:34