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


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));

我需要改进这段代码。

我已经尝试改进变量描述。下面是使用改进的变量

的代码
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));

在这段代码中我还可以尝试改进什么?

您可以添加一个带有简短if语法的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));

或者使用forEachJavaScript语法,你可以使用:

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

同样,你可以在item对象本身中添加factor属性到'特殊'项(factor != 1),像这样:

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

那么您可以像这样使用reduce方法:

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

或只是:

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

最新更新