在JavaScript中比较变量点与最高匹配截止值/数组阈值

时间:2015-06-16 13:07:31

标签: javascript json

我的JavaScript示例中运行了一个变量var runs = 14;我还有一个包含[{"10":"lowestscore"},{"13":"lowscore"},{"20":"okscore"}]的阈值数组。

我希望通过最高匹配运行阈值和运行来打印与变量对应的消息。此处的示例输出应为lowscore,为14匹配,13为最高阈值。

请建议一种有效的计算方法。

我正在尝试

$.each(runsThresholdArray, function (index, value) {
 while (value.key <  runs) {
             // some logic
              }
             })

;

由于

4 个答案:

答案 0 :(得分:1)

这样的事情可以解决问题:

var tresholds = [{"10":"lowestscore"},{"13":"lowscore"},{"20":"okscore"}];
var runs = 14;

var result = { value: 0 }; // Result variable, the end result is stored in this.

for(var i = 0; i < tresholds.length; i++){             // Iterate over all tresholds.
  var value = parseInt(Object.keys(tresholds[i])[0]); // Get the current treshold's value.
  if(value > result.value && value <= runs){         // If the value is higher than any previous result, but not too high,
    result.value = value;                           // Remember the current result
    result.text = tresholds[i][value];
  }
}

alert(JSON.stringify(result)) // `result.value` is the number, `result.text` is the text.

答案 1 :(得分:0)

没有jQuery,假设数组没有排序,但内容格式正确,只包含此处显示的单个属性。

var threshold =  [{"10":"lowestscore"},{"13":"lowscore"},{"20":"okscore"}],
    runs = 14;

var getMessage = function (threshold, runs) {
    var onlyPropertyToInt = function (obj) {
        return parseInt(Object.getOwnPropertyNames(obj));
    };

    return threshold.sort(function(a,b){
            return onlyPropertyToInt(a)-onlyPropertyToInt(b)
        }).reduce(function (memo, item){
            var num = onlyPropertyToInt(item);
            if (num < runs) { memo = item[''+num] }
            return memo;
        }, null);
}

getMessage(threshold, runs);

效率不应该是一个问题,除非你在这里有数以千计的门限数千个电话。

答案 2 :(得分:0)

我认为你正在为你的threshold浪费一个非常好的数据结构:一个对象。更容易管理而不是一组对象:

var threshold = {
    45: "hooray" ,
    13: "lowscore" ,
    20: "okscore" ,
    100: "god like" ,
    10: "lowestscore",
    25: "notbad",
    2: "uh oh"
}

var runs = 100;

function getThreshold(runs, threshold) {

    // get a list of your object keys, convert them to an integer
    // and then sort them
    var keys = Object.keys(threshold)
                     .map(Number)
                     .sort(function (a, b) { return a - b; });

    // loop over the keys
    for (var i = 0, l = keys.length; i < l; i++) {

        // get the difference between `runs` and the current
        // element, and `runs` and the next element
        var diff = Math.abs(runs - keys[i]);
        var diffNext = Math.abs(runs - keys[i + 1]);

        // store the resulting notification from the
        // threshold object
        var tmp = threshold[keys[i]];

        // if the current difference is greater than the
        // difference of the next element, continue to the
        // next element, otherwise break out of the loop
        // and return the notification
        if (diff <= diffNext) { break; }
    }
    return tmp;
}

getThreshold(100, threshold); // god like
getThreshold(14, threshold); // lowscore
getThreshold(2, threshold); // uh oh
getThreshold(24, threshold); // notbad

DEMO

答案 3 :(得分:-2)

var runsThresholdArray = **{{**"10":"lowestscore"},{"13":"lowscore"},{"20":"okscore"**}}**;
$.each(runsThresholdArray, function **(key, value)** {
        while (**key** <  runs) {
             // some logic
        }
 });

您的错误:不是索引,值//使用:键,值 index用于非配对/非关联数组: 你的数组相当 - 概念上 - 一个对象。 使用{}而不是[](请参阅我的代码)。顺便提一下,您将有一种更简单的方法来解析它。

JQuery doc(http://api.jquery.com/jquery.each/):

var obj = {
  "flammable": "inflammable",
  "duh": "no duh"
};
$.each( obj, function( **key, value** ) {
  alert( key + ": " + value );
});