向后计算Javascript数组 [英] Calculate backwards in a Javascript array
问题描述
这里是我目前正在工作的JsFiddle .
我有2个产品1 and 2
然后我必须为用户选择3种样式的产品:s1,s2 and s3
Then I have 3 STYLES for those products a user MUST select : s1,s2 and s3
然后,我有了一个价格表,该价格表会随着人们选择的数量和样式而变化.见下文
Then I have table of prices that changes with the quantity and style people choose. See below
这是我的数组.
数量
Quantity : [ 50, 100, 150, 200, 250]
所有3种样式的商品1的价格
p1s1 : [2.00, 1.80, 1.60, 1.40, 1.20]
p1s2 : [2.10, 2.00, 1.80, 1.60, 1.40]
p1s3 : [2.25, 2.15, 2.05, 1.95, 1.75]
p1s1 : [2.00, 1.80, 1.60, 1.40, 1.20]
p1s2 : [2.10, 2.00, 1.80, 1.60, 1.40]
p1s3 : [2.25, 2.15, 2.05, 1.95, 1.75]
所有3种样式的产品2价格
p2s1 : [3.00, 2.80, 2.60, 2.40, 2.20]
p2s2 : [3.10, 3.00, 2.80, 2.60, 2.40]
p2s3 : [3.50, 3.30, 3.00, 2.80, 2.50]
p2s1 : [3.00, 2.80, 2.60, 2.40, 2.20]
p2s2 : [3.10, 3.00, 2.80, 2.60, 2.40]
p2s3 : [3.50, 3.30, 3.00, 2.80, 2.50]
这里是我目前正在使用JsFiddle的.
我的问题
我想创建一个可以向后工作的新计算器.也就是说,当某人输入手中的金额时,例如250美元,计算器应显示某人可以用这些钱购买多少个(数量)产品1s和2s.因此它应该显示如下.
I want to create a new calculator that works backwards. That is, when someone inputs the amount of money they have in hand, let's say $250, the calculator should display how many (quantity) Product 1s and 2s someone can purchase with that money. So it should display like below.
产品1,样式1-数量150 = $ 240
产品1,样式2-数量138 = $ 248.40
产品1,样式3-数量121 = $ 248.05
让我知道我是否不清楚.提前非常感谢.
Let me know if Im not clear. Thanks so much in advance.
推荐答案
function getAffordibiltyObject(OB, money)
{
var afford = {};
for (var code in OB){
if(/p\ds\d/.test(code)){
for (var i=0; i<OB[code].length; i++){
if(money < OB[code][i]*OB.qtty[i] || i==OB[code].length-1){
var price = OB[code][i];
var quantity = Math.floor(money/price);
var total = quantity*price;
afford[code] = [quantity, total];
}
}
}
}
return afford;
}
var OB = {
wrap : 0.05,
// quantities
qtty : [ 50, 100, 150, 200, 250],
// product 1
p1s1 : [2.00, 1.80, 1.60, 1.40, 1.20],
p1s2 : [2.10, 2.00, 1.80, 1.60, 1.40],
p1s3 : [2.25, 2.15, 2.05, 1.95, 1.75],
// product 2
p2s1 : [3.00, 2.80, 2.60, 2.40, 2.20],
p2s2 : [3.10, 3.00, 2.80, 2.60, 2.40],
p2s3 : [3.50, 3.30, 3.00, 2.80, 2.50]
};
var money = 250;
var affordibilityOB = getAffordibiltyObject(OB, money);
这就是您要寻找的affordabilityabilityOB将是一个具有p1s1,p2s2等键的对象,并且值将是一个长度为两个的数组,第一个元素为结果数量,第二个为结果总计.
This is what you are looking for affordibilityOB will be an object with keys like p1s1 , p2s2 ... and the values will be an array of length two first element being result quantity and second being result total.
这篇关于向后计算Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!