简体   繁体   English

此代码计算项目列表的总价,但我该如何改进它?

[英]This code calculates the total price of a list of items but how can i improve it?

function calculateTotal(items) {
  let total = 0;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type === "food") {
      total += items[i].price * 1.1;
    } else {
      total += items[i].price;
    }
  }
  return total;
}

const items = [
  { type: "food", price: 10 },
  { type: "clothing", price: 20 },
  { type: "electronics", price: 30 }
];

console.log(calculateTotal(items));

I need to improve on this code.我需要改进这段代码。

I have tried improving the variable description.我尝试改进变量描述。 here is the code again with improved variables这是带有改进变量的代码

function calculateTotal(items) {
  let total = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.type === "food") {
      total += item.price * 1.1;
    } else {
      total += item.price;
    }
  }
  return total;
}

const items = [
  { type: "food", price: 10 },
  { type: "clothing", price: 20 },
  { type: "electronics", price: 30 }
];

console.log(calculateTotal(items));

what else can i try improving on in this code?我还可以尝试在此代码中改进什么?

You can add a factor const with shorted if syntax for better readability您可以使用 shorted if 语法添加一个 factor const 以获得更好的可读性

function calculateTotal(items) {
  let total = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    const factor = (item.type === "food") ? 1.1 : 1
    total += item.price * factor;
  }
  return total;
}

const items = [
  { type: "food", price: 10 },
  { type: "clothing", price: 20 },
  { type: "electronics", price: 30 }
];

console.log(calculateTotal(items));

Or using forEach JavaScript syntax you can use:或者使用forEach JavaScript 语法,您可以使用:

function calculateTotal(items) {
  let total = 0;
  items.forEach((item) => {
    total += ((item.type === "food") ?  item.price * 1.1 : item.price) 
    })
  return total;
}

Also, you can add factor property inside the item object itself to 'special' items (with factor:= 1) like this:此外,您可以将项目对象本身内的因子属性添加到“特殊”项目(因子:= 1),如下所示:

const items = [
  { type: "food", price: 10, factor: 1.1 },
  { type: "clothing", price: 20 },
  { type: "electronics", price: 30 }
];

Than you can use the reduce method like this:你可以像这样使用reduce方法:

function calculateTotal(items) {
  let total = items.reduce((acc, item) => {
    return acc + item.price * (item?.factor || 1)
    }, 0)
  return total;
}

Or just:要不就:

function calculateTotal(items) {
  return items.reduce((acc, item) => {
    return acc + item.price * (item?.factor || 1)
    }, 0)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM