繁体   English   中英

将JSON数组与用户输入进行比较并获取值

[英]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;
}

说明:

  • 设置一个变量,它将作为我们的返回值到第一个边界
  • 循环通过边界,如果输入小于当前边界且大于前一个边界,则将其设置为out值(注意:我们将idx !== 0跳过了第一次迭代,因为我们将其设置为out已经值)
  • 通过这种方法,我们应该到达输入之间的边界,并返回该值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM