0

I need to create a JavaScript function that uses an array to hold the values: ["00", "33", "66", "99", "CC", "FF"]. I then need to loop through the array and display all 216 web safe colors as hexadecimal values on my page. The code below is what I have so far but I am not sure about looping through to create the rest of the numbers.

function displayColors() {
    var hex1;
    var hex2;
    var hex3;
    var clr;
    var steps = [
        '00',
        '33',
        '66',
        '99',
        'cc',
        'ff' 
    ];
    var arrLength = steps.length;
    var counter = 1; // Make sure there are 216 colors displayed

        for (var b = 0; b < arrLength; b++) {
            hex1 = steps[b];
            hex2 = steps[b];
            hex3 = steps[b];
            clr = hex1 + hex2 + hex3;
            document.getElementById("display").innerHTML += 
                "<div>" + counter + ": " + clr + "</div>";
            counter++;
        }
}
Gerardo
  • 979
  • 1
  • 7
  • 15

3 Answers3

1

Change your for loop to this:

 for (var a = 0; a < arrLength; a++) {
        for (var b = 0; b < arrLength; b++) {
            for (var c = 0; c < arrLength; c++) {
                hex1 = steps[a];
                hex2 = steps[b];
                hex3 = steps[c];
                clr = hex1 + hex2 + hex3;
                document.getElementById("display").innerHTML += "<div>" + counter + ": " + clr + "</div>";
                counter++;
            }
        }
    }
Paul
  • 111
  • 4
  • Thank you that worked perfectly. However I am not sure exactly how it works out? – dkjason2011 Mar 01 '17 at 21:28
  • When it was a single loop you were just moving along the same index of the array for each color ff ff ff, 00 00 00, etc, What you needed was to be able to step through each index independently for each of the 3 places hence 3 for loops – Paul Mar 01 '17 at 21:38
1

This is the loop that you need:

Here's the fiddle:

JSFiddle

var steps = ['00', '33', '66', '99', 'cc', 'ff'];
for(var i = 0; i < steps.length; i++){
  for(var j = 0; j < steps.length; j++){
    for(var k = 0; k < steps.length; k++){
        console.log(steps[i] + steps[j] + steps[k]);
    }
  }
}
Gerardo
  • 979
  • 1
  • 7
  • 15
1

If you insist on using your array, have a look at Generating combinations from n arrays with m elements - which you could use as cartesian(steps, steps, steps).map(parts => parts.join("")).

However, there's a much easier way than to deal with hex string arrays. Use plain numbers:

for (var r=0; r<=0xFF0000; r+=0x330000)
    for (var g=0; g<=0xFF00; g+=0x3300)
        for (var b=0; b<=0xFF; b+=0x33)
            console.log( (r|g|b).toString(16).padStart(6, "0") );
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375