JavaScript 发票打印与总价计算解决方案

// 1. 将产品字符串转换为数组
const productStrings = [
  "Shoes:23.99",
  "T-shirt:15.99",
  "Jeans:49.99",
  "Hat:12.99"
];
const products = productStrings; // number 1

let total = 0;

// 2. 修正for循环条件
for (let i = 0; i < products.length; i++) { // number 2
  // 3. 分割产品名称和价格,并将价格转为数字
  const [name, priceStr] = products[i].split(':');
  const price = parseFloat(priceStr); // number 3
  
  // 4. 累加价格到总价
  total += price; // number 4
  
  // 5. 格式化项目文本
  const itemText = `${name} - $${price.toFixed(2)}`; // number 5   console.log(itemText); }  console.log(`Total: $${total.toFixed(2)}`);

你可能感兴趣的:(javascript,前端,开发语言)