你可能想要一个像这样的数据结构:
products = {
7: {
id: 7,
title: "My Product",
// note that the prices are in increasing order of minimum threshold
// for quantity (i.e. 0 for 0-500, THEN 500 for 500-1000 THEN
// 1000 for 1000-5000, etc., in that order)
price: {
0: 20,
500: 17,
1000: 13
}
},
10: {
id: 10,
title: "My Other Product",
price: {
0: 50,
500: 45,
1000: 40
}
},
...
}
接下来,计算产品 X 的价格(即 id = X)和数量 Q:
var correctPrice = -1;
for (var threshold in products[X].price) {
if (Q >= threshold)
correctPrice = products[X].price[threshold];
}
if (correctPrice > -1)
// use correctPrice here
使用它,您可以拥有任意数量的具有任意数量阈值和价格的产品,并以编程方式使用正确的价格进行计算。