gpt4 book ai didi

javascript - 在javascript对象中找到最接近的低 "key"

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:35:41 26 4
gpt4 key购买 nike

我正在使用 javascript 对象,虽然我有一个解决方案,但我认为它可以更有效地完成。

对象是从对 php 脚本的 ajax 调用返回的

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

//等等...

console.log(r.price_array[price_set]); //this returns the value

有没有办法取数量 3 并找到下一个最低键匹配项,即 1?或数量 7 并找到键 5?

最佳答案

我的版本(已测试, fiddle 在这里:http://jsfiddle.net/fred02138/UZTbJ/):

// assume keys in rprice object are sorted integers
function x(rprice, qty) {
var prev = -1;
var i;
for (i in rprice) {
var n = parseInt(i);
if ((prev != -1) && (qty < n))
return prev;
else
prev = n;
}
}

var rprice = {
1: 39.99,
5: 24.99,
10: 19.99
}

alert(x(rprice, 3));
alert(x(rprice, 7));

关于javascript - 在javascript对象中找到最接近的低 "key",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18410724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com