【发布时间】:2021-06-02 20:55:09
【问题描述】:
由于所有 3 种功能的产品都相似,因此价格有所不同。那么有什么方法可以让我将所有产品保存在一个函数中并将它们调用到另外两个函数中,并且只更改最后两个函数中的价格?我不想为每种类型重复代码
由于有三个功能,并且由于它是重复的,我想只保留一个主功能,然后将产品列表从主功能调用到除价格之外的其他两个功能。因为每个人的价格都不一样。有人可以让我知道该怎么做吗?如何在不重复的情况下调用另一个函数内部的函数?
我想将产品列表从主函数调用到另外两个函数,因此我不重复代码,并且我希望在这两个函数中只添加价格。我该怎么做?
有人可以告诉我我必须对代码进行哪些更改才能实现它吗?
谢谢
Product.js
function ProductDataConsolidator() { }
ProductDataConsolidator.get = function () {
var l = new LawnmowerRepository().getAll();
var p = new PhoneCaseRepository().getAll();
var t = new TShirtRepository().getAll();
var products = [];
for (var i = 0; i < l.length; i++) {
products.push({
id: l[i].id,
name: l[i].name,
price: l[i].price.toFixed(2),
type: "Lawnmower"
});
}
for (var i = 0; i < p.length; i++) {
products.push({
id: p[i].id,
name: p[i].name,
price: p[i].price.toFixed(2),
type: "Phone Case"
});
}
for (var i = 0; i < t.length; i++) {
products.push({
id: t[i].id,
name: t[i].name,
price: t[i].price.toFixed(2),
type: "T-Shirt"
});
}
return products;
}
ProductDataConsolidator.getInUSDollars = function () {
var l = new LawnmowerRepository().getAll();
var p = new PhoneCaseRepository().getAll();
var t = new TShirtRepository().getAll();
var products = [];
for (var i = 0; i < l.length; i++) {
products.push({
id: l[i].id,
name: l[i].name,
price: (l[i].price * 0.76).toFixed(2),
type: "Lawnmower"
});
}
for (var i = 0; i < p.length; i++) {
products.push({
id: p[i].id,
name: p[i].name,
price: (p[i].price * 0.76).toFixed(2),
type: "Phone Case"
});
}
for (var i = 0; i < t.length; i++) {
products.push({
id: t[i].id,
name: t[i].name,
price: (t[i].price * 0.76).toFixed(2),
type: "T-Shirt"
});
}
return products;
}
ProductDataConsolidator.getInEuros = function () {
var l = new LawnmowerRepository().getAll();
var p = new PhoneCaseRepository().getAll();
var t = new TShirtRepository().getAll();
var products = [];
for (var i = 0; i < l.length; i++) {
products.push({
id: l[i].id,
name: l[i].name,
price: (l[i].price * 0.67).toFixed(2),
type: "Lawnmower"
});
}
for (var i = 0; i < p.length; i++) {
products.push({
id: p[i].id,
name: p[i].name,
price: (p[i].price * 0.67).toFixed(2),
type: "Phone Case"
});
}
for (var i = 0; i < t.length; i++) {
products.push({
id: t[i].id,
name: t[i].name,
price: (t[i].price * 0.67).toFixed(2),
type: "T-Shirt"
});
}
return products;
}
【问题讨论】:
标签: javascript arrays list