我正在处理一个JavaScript对象,虽然我已经有了解决方案,但我仍然认为它可以更有效地完成。
该对象是从一个ajax调用php脚本返回的。
r.price_array[1] = 39.99
r.price_array[5] = 24.99
r.price_array[10] = 19.99
and so on....
我现在正在搜索关键值(关键值表示数量)。
qty = $(this).val();
if (qty >= 1 && qty <= 4){
price_set = 1;
}
else if (qty >= 5 && qty <= 9){
price_set = 15;
}
else if (qty >= 10 && qty <= 14){
price_set = 25;
}
//and so on...
console.log(r.price_array[price_set]); //this returns the value
有没有办法找到数量为3的下一个最低键匹配项,这将是1吗? 或者数量为7,找到键5?
[1] [2] [3] [4]
都包含39.99,然后if (quantity <= max) pricePerUnit = prices[quantity]
。 - Stephen P