我正在构建某种计算器,用户可以输入他的收入,然后函数在JSON数组上迭代以找到相应的数字。它应该是这样的:
if (z >= x && z <= y)
其中z是用户输入,x和y是双方的限制。
这是JSON数组(只有3个100):
[["0",0],["1",898],["2",12654],["3",15753]]
我不知道怎么写这个功能。我可以使用100 ifs和elseifs来做到这一点。但我很确定有更好的方法。
答案 0 :(得分:1)
基本上,你需要遍历每个界限,以找到人的收入来源,例如。
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值))