[英]Comparing JSON array with user input and get a value
我正在构建某种计算器,用户可以在其中输入其收入,然后该函数在JSON数组上进行迭代以找到相应的数字。 应该是这样的:
if (z >= x && z <= y)
其中z是用户输入,x和y是两侧的限制。
这是JSON数组(100个中只有3个):
[["0",0],["1",898],["2",12654],["3",15753]]
我不知道该怎么写这个函数。 我可以用100 ifs和elseifs来做。 但是我很确定有更好的方法。
本质上,您需要遍历每个边界以找到人员收入所在的位置,例如
function getIncomeBound(input) {
//Note: this is not the best way to store this data but that's another issue
var bounds = [["0",0],["1",898],["2",12654],["3",15753]];
var out = bounds[0];
bounds.forEach(function (el, idx) {
out = (idx !== 0 && input <= el[1] && input > bounds[idx - 1][1] ? el : out);
});
return out;
}
说明:
idx !== 0
跳过了第一次迭代,因为我们将其设置为out已经值)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.