Skip to content Skip to sidebar Skip to footer

Array Index N.o. + Value

Hi I have a post here http://jsfiddle.net/7ztEf/9/ that explains what i want to achieve. I will break it down, I need to fill a div bg based on the values of an array index, these

Solution 1:

For just a few colors I would just write it out like this:

for (var x = 0, n = numbers.length; x != n; ++x) {
    var nr = numbers[x], 
        el = document.getElementById(type + x),
        color;

   el.innerHTML = nr;

    if (nr > 0) {
        if (nr <= 10) {
            color = 'red';
        } elseif (nr <= 20) {
            color = 'blue';
        } elseif (nr <= 30) {
            color = 'orange';
        } elseif (nr <= 40) {
            color = 'green';
        }
    }
    if (color) {
        el.style.color = color;
    }
} 

Demo

Solution 2:

Try this..

for (var x = 0;x<numbers.length;x++) {

    el = document.getElementById(type + x);

el.innerHTML = nr;

if (nr > 0) {
    if (nr <= 10) {
        color = 'red';
    } elseif (nr <= 20) {
        color = 'blue';
    } elseif (nr <= 30) {
        color = 'orange';
    } elseif (nr <= 40) {
        color = 'green';
    }
}
if (color) {
    document.getElementById('ball-' + x).style.backgroundColor = color;
}
} 

Solution 3:

I'd do something like this:

var colors = ['red', 'blue', 'orange', 'green'];

functionmyNumbers(numbers, type) {
    for (var i = 0; i < numbers.length; i++) {
        varnumber = numbers[i];
        var color = colors[Math.floor(number / colors.length)];

        document.getElementById(type + i).innerHTML = number;
        document.getElementById('ball-' + i).style.backgroundColor = color;
    }
}

Don't iterate over arrays with the for...in syntax. That iterates over the properties of an object.

Post a Comment for "Array Index N.o. + Value"