0

我有类似的东西

var keyVals = Array;
keyVals['23'] = 234;
keyVals['58'] = 'sunshine';
keyVals['172'] = 'lolipops';

newVar = 76;

我怎样才能找到数组中的哪个键的值(一旦变成数字)最接近我的 newVar?23、58、172 中哪个最接近我的 76?

谢谢

4

4 回答 4

1

首先,请注意您在技术上创建一个对象,因此 keyVals 的首选分配是keyVals = {}.

var newVar = 31,
    keyNum,
    key,
    diff,
    keyVals = {},
    closest = {
        key: null,
        diff: null
    };

keyVals['23'] = 234;
keyVals['58'] = 'sunshine';
keyVals['172'] = 'lolipops';

for(key in keyVals) {
    if(keyVals.hasOwnProperty(key)) {
        keyNum = parseInt(key,10);
        diff = Math.abs(newVar - keyNum);

        if(!closest.key || diff < closest.diff) {
            closest.key = key;
            closest.diff = diff;
        }
    }
}

for循环完成后,将closest.key包含最近匹配的索引newVar。为了增加保护,请使用hasOwnProperty以确保您不会意外地迭代keyVals原型之一的属性(当然,在这种特定情况下这不太可能)。

于 2012-08-16T14:16:33.310 回答
0

首先:
如果你使用数字类型的值作为你的键,它们必须是数字。
它应该是 23,而不是 '23'
否则 23 将被视为字符串 '23',不能针对数字进行数学测试。

var keyVals = Array;
keyVals[23] = 234; // keyVals[23], not keyVals['23']
keyVals[58] = 'sunshine';
keyVals[172] = 'lolipops'

要找到最近的键,
只需遍历您的键并搜索最近的键。

dist = Number.POSITIVE_INFINITY; // set the distance from key to value
closestkey = -1; // closest key variable
for(i in keyVals) {
    // i is the key, keyVals[i] is the value
    newdist = Math.abs(newVar - i); // distance from current key to value
    if (newdist < dist) {
        // we found a key closer to the value
        dist = newdist; // set new smallest distance
        closestkey = i; // set the value to the current key
    }
}
// Now closestkey is the key to your closest variable
于 2012-08-16T14:14:04.703 回答
0

正如其他人指出的那样,Objects当您想要将键映射到值时,(又名哈希)是使用的最佳数据结构;考虑到这一点,您将看到将映射键预排序为数字顺序的性能优势。

// Helper method, you could also use underscore.js's `_.keys`
function getKeys(object) {
    var keys = [];
    for (var key in object) {
        if (object.hasOwnProperty(key)) {
            keys.push(key);
        }
    }
    return keys;
};

// Lookup table.
var keyVals = {
    23: "234",
    58: "sunshine",
    172: "lollypops"
};

// Extract the keys from the lookup table and sort them into numerical order.
var sortedKeys = getKeys(keyVals).sort(function (a, b) {
    return a - b;
});

// Returns the closest key in the `keyVals` lookup table for the supplied value.
function getClosestIndex(value) {
    var i;

    // Walk through the sorted keys array and stop when the next value is greater.
    for (i = 0; i < sortedKeys.length; i++) {
        if (sortedKeys[i] > value) {

            // Either return the previous key, or zero if this was the first.
            return (i === 0) ? sortedKeys[0] : sortedKeys[i - 1];
        }
    } 

    // We reached the end, so the value is greater than the highest key we have.
    return sortedKeys[i];
}

显然,如果您的keyVals地图很小(少于 1000 个条目),那么这种优化是相当学术的(但仍然很有趣):)

于 2012-08-16T14:30:16.933 回答
0

但请注意,可能有 2 个值最接近newVar.

例如:

keyVals[23] = 234;
keyVals[129] = 'aaa';
keyVals[172] = 'lolipops';

23 和 129 都最接近 76。

然后,

var keyVals = Array;
keyVals[23] = 234;
keyVals[129] = 'aaa';
keyVals[172] = 'lolipops';
newVar = 76;
var closest=new Object();
for(var i in keyVals){
    if(typeof closest.dif=='undefined'){
        closest.dif=Math.abs(newVar-i);
        closest.val=[i];
    }else{
        if(closest.dif==Math.abs(newVar-i)){
            closest.val.push(i);
        }else if(closest.dif>Math.abs(newVar-i)){
            closest.dif=Math.abs(newVar-i);
            closest.val=[i];
        }
    }
}
alert("The closest keys to "+newVar+" are ["+closest.val.join(',')+"], with a difference of "+closest.dif);

将提醒“最接近 76 的键是 [23,129],相差 53”

或者用你的阵列,

keyVals[23] = 234;
keyVals[58] = 'sunshine';
keyVals[172] = 'lolipops';

会提示“最接近 76 的键是 [58],相差 18”

于 2012-08-16T14:25:55.647 回答