如何在从对象返回数据时检查间接匹配?

时间:2012-10-09 17:56:27

标签: javascript object

我想在我的数组中检查一个变量。如果数字直接与我的值匹配,它就有效。如果它低于匹配,我怎样才能使它与之前的值匹配。从我的代码:

var assassin_bp = {
    fhr: { 7:8, 15:7, 27:6, 48:5, 86:4, 200:3 },
    fcr: { 8:15, 16:14, 27:13, 42:12, 65:11, 102:10, 174:9 }
}
var char_fhr = 48;
var fhr_frames = assassin_bp[ 'fhr' ][ [char_fhr] ]

char_fhr 48 fhr_frames 返回 5
如果 char_fhr 47 (或27到47之间的任何数字), fhr_frames 应返回 6
如果 char_fhr 49 (或48到85之间的任何数字), fhr_frames 应返回 5

我对从哪里开始毫无头绪。对象可以包含范围吗?我应该有功能检查吗?

2 个答案:

答案 0 :(得分:2)

您需要迭代对象属性并将其名称与目标值进行比较。请参阅for...in [MDN]Working with Objects [MDN]

function valueForClosestKey(obj, target) {
    // get all keys smaller than or equal to `target`
    var keys = [];
    for(var k in obj) {
        if(k <= target) {
            keys.push(k);
        }
    }

    // order keys in ascending order
    keys.sort(function(a, b) {
        return a - b;
    }); 
    // e.g. `keys` is now [7, 15, 27, 48]      

    // get the "closest" key, which is the last one in the array
    if(keys.length > 0) {
        return obj[keys.pop()];
    }
    // if there are no keys smaller than `target` (i.e. `keys` is empty),
    // we just don't return anything (implicitly returns `undefined`)
}

var value = valueForClosestKey(assassin_bp[ 'fhr' ], char_fhr);

有必要以这种方式提取和排序键,因为迭代对象的顺序取决于实现。即不能保证属性的数字顺序正确。

答案 1 :(得分:1)

http://jsfiddle.net/aquinas/QP6aF/

怎么样:

var assassin_bp = {
    fhr: { 7:8, 15:7, 27:6, 48:5, 86:4, 200:3 },
    fcr: { 8:15, 16:14, 27:13, 42:12, 65:11, 102:10, 174:9 }
}

var arr = [];

for (var prop in assassin_bp.fhr){
    if (assassin_bp.fhr.hasOwnProperty(prop)){
        arr.push(parseInt(prop));
    }
}

arr.sort(function(a,b){return a-b;});

function calcScore(val){
    if (arr[0] > val){
        return assassin_bp.fhr[arr[0]];
    }

    for (var i=arr.length; i>=0; i--){
        if (val >= arr[i]){
            return assassin_bp.fhr[arr[i]];
        }
    }
}

//test to see if this works:
for (var i=0; i<300; i++){
    document.write(i + " - " + calcScore(i) + "<br/>");
}                    
        ​