Get the next and previous element of the array, taking into account the index

Given that I have an array in Javascript with values ​​as such,

0     => 0x0000FF
1200  => 0x00CCFF
28800 => 0xFF0AFF
36000 => 0xFFFFFF

How to determine which elements have an index value? In the previous example, if I have a value of 31073, I need to get 28800 => 0xFF0AFFand36000 => 0xFFFFFF

+3
source share
3 answers

I just wanted to trace here;

< quixoto patrick dw. , , . , , , , . , , .

var colors = [  
    [0,     '121D4A'],
    [10800, '000000'],
    [21600, 'FF5900'],
    [32400, 'D3EEF0'],
    [43200, '7DCDFF'],
    [54000, '7DA6FF'],
    [64800, 'FF5900'],
    [75600, '31428C'],
    [86399, '121D4A'],
];

function gradientStop(color1, color2, gradStop){
    var r = Math.floor(gradStop * parseInt(color2.substr(0, 2), 16) + (1 - gradStop) * parseInt(color1.substr(0, 2), 16)).toString(16);
    var g = Math.floor(gradStop * parseInt(color2.substr(2, 2), 16) + (1 - gradStop) * parseInt(color1.substr(2, 2), 16)).toString(16);
    var b = Math.floor(gradStop * parseInt(color2.substr(4, 2), 16) + (1 - gradStop) * parseInt(color1.substr(4, 2), 16)).toString(16);
    return (r.length < 2 ? '0' + r : r) + (g.length < 2 ? '0' + g : g) + (b.length < 2 ? '0' + b : b);
}

function getColor(colors, currentIndex){
    for(var i = 0, m = colors.length; i < m; i++){
        if(currentIndex >= colors[i][0]){
            if(typeof(colors[i + 1]) !== 'undefined'){
                if(currentIndex <= colors[i + 1][0]){
                    return gradientStop(colors[i][1], colors[i + 1][1], (currentIndex - colors[i][0]) / (colors[i + 1][0] - colors[i][0]));
                }
            }
        }
    }
}

; Hemlock, Javascript, , gradientStop().

+1

"" Javascript. , , - . lookaside, , , .

O (), lookaside.

+2

, while() .

, . , .

Also, I was not sure what would happen if the starting point is right on the color, so I did not take this into account.

Example: http://jsfiddle.net/tcVxP/4/

var num = 31234,
    curr = num,
    prev,
    next;

while( !colors[--curr] && curr );
prev = colors[curr];

curr = num;
while( !colors[++curr] );
next = colors[curr];
+2
source

Source: https://habr.com/ru/post/1783135/


All Articles