Skip to content Skip to sidebar Skip to footer

Random Hex Color

This is the javascript to generate a random hex color: '#'+(Math.random()*0xFFFFFF<<0).toString(16); could anyone talk me through it? I understand how the Math.random work

Solution 1:

It looks like you picked this up on codegolf.

How can Math.random() multiplied by F output a number?

It is not multiplied by F. 0xFFFFFF is converted to 16777215, as 0xFFFFFF is just the hexadecimal way of writing 16777215.

What does the <<0 mean?

<< is a bitshift operator. <<0 shifts all bits 0 places to the left (filler: 0). This doesn't make any sense though. In this case it just deletes any decimal places.

What does the parameter of 16 on toString mean? (does it mean no more than 16 letters?)

The 16 is the parameter for the numeral system. (2 is binary, 8 is octal, 10 is decimal/normal, 16 is hexadecimal, etc.).

Solution 2:

The best way to generate random HEX color:

It contains of tow functions:

  1. The fest one picks a random hex number.

  2. and the second one creates an array with hex values.

    // Returns one possible value of the HEX numbers

    functionrandomHex() {
        var hexNumbers = [
        0,
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        'A',
        'B',
        'C',
        'D',
        'E',
        'F'
    ]
    
        // picking a random item of the arrayreturn hexNumbers[Math.floor(Math.random() * hexNumbers.length)];
    }
    
    
    // Genarates a Random Hex colorfunctionhexGenerator() {
        hexValue = ['#'];
        for (var i = 0; i < 6; i += 1) {
            hexValue.push(randomHex());
        }
    
        return hexValue.join('');
    }
    
    
    // print out the random HEX colordocument.write(hexGenerator());
    

good luck

Post a Comment for "Random Hex Color"