简体   繁体   English

在jQuery中使用一个关联数组而不是两个索引数组

[英]Use one Associative Array instead of two index arrays in jQuery

Fiddle Example 小提琴的例子

I'm making a function to return the next nearest number and the associated color from a value,like if the value is 500 , the function will return 600 and its associated color beige . 我正在使一个函数从值返回下一个最接近的数字和相关颜色,例如,如果该值为500 ,则该函数将返回600及其相关颜色beige I'm using two arrays, one for the numbers, and the other for the colors to accomplish that. 我正在使用两个数组,一个用于数字,另一个用于颜色来实现此目的。 I 'd like to know if that's the right way of doing things like that. 我想知道这是做这样事情的正确方法。 Instead of two separate arrays, can I just use one associative array to get the result? 代替两个单独的数组,我可以只使用一个关联数组来获得结果吗?

Instead of: 代替:

var array = [50,100,200,400,600,1000,1500]
var color = {50:"red",100:"yellow",200:"Golden",400:"Black",600:"beige",1000:"pink",1500:"green"};

Is it possible to use something like that: 是否可以使用类似这样的东西:

var array ={50:"red",100:"yellow",200:"Golden",400:"Black",600:"beige",1000:"pink",1500:"green"};

Here's the example: 例子如下:

var array = [50,100,200,400,600,1000,1500]
var color = {50:"red",100:"yellow",200:"Golden",400:"Black",600:"beige",1000:"pink",1500:"green"};

var getClosestValues = function(a, x) {
    var lo, hi;
    for (var i = a.length; i--;) {
        if (a[i] <= x && (lo === undefined || lo < a[i])) lo = a[i];
        if (a[i] >= x && (hi === undefined || hi > a[i])) hi = a[i];
    };
    var text = [];
    var text = [x+'/'+hi,color[hi]];
    return text;
}

var print = getClosestValues(array,1411);
$('.area').html('<div style="background:'+print[1]+'">'+print[0]+'</div>');

Sure thing. 当然可以 Here's a fork of your fiddle, iterating over the associative array keys and not using the separate array: http://jsfiddle.net/65nb1cmo/1/ 这是您的小提琴的一部分,在关联的数组键上进行迭代,而不使用单独的数组: http : //jsfiddle.net/65nb1cmo/1/

Since you're using jQuery, we can use their nice each iterator. 由于您使用的是jQuery,我们可以在each迭代器中使用它们。 Our strategy is simply to look at each key/value pair in the associative array (where the key is stored in i each iteration as before). 我们的策略是简单地查看关联数组中的每个键/值对(其中键像以前一样在每次迭代中存储在i )。 We find the nearest i to the provided x , and then return it. 我们找到最接近提供的x i ,然后将其返回。

var color = {50:"red",100:"yellow",200:"Golden",400:"Black",600:"beige",1000:"pink",1500:"green"};

var getClosestValues = function(a, x) {
    var lo, hi;
    $.each(a, function(i, name) {
        if (i <= x && (lo === undefined || lo < i)) lo = i;
        if (i >= x && (hi === undefined || hi > i)) hi = i;
    });
    var text = ''+x+'/'+hi+','+color[hi]+'';
    return text;
}

var print = getClosestValues(color,1411);
print = print.split(',');
$('.area').html('<div style="background:'+print[1]+'">'+print[0]+'</div>');

您可以使用Object.keys(color)获取包含对象中所有键的数组。

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

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