简体   繁体   中英

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 . 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/

Since you're using jQuery, we can use their nice each iterator. 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). We find the nearest i to the provided x , and then return it.

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)获取包含对象中所有键的数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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