This article introduces several implementation methods of JavaScript random color code. For more information about JS random colors, see. JS random colors. For example, you can see that many tag connections are colorful. That's all we need. Start as follows:
There are two methods in total.One is to prepare a set of beautiful candidate colors, and the other is to randomly generate colors..
Implementation 1
The Code is as follows:
Var getRandomColor = function (){
Return '#' +
(Function (color ){
Return (color + = '0123456789abcdef '[Math. floor (Math. random () * 16)])
& (Color. length = 6 )? Color: arguments. callee (color );
})('');
}
The six characters are randomly generated and then stringed together. The closure calls itself and the ternary operator make the program restrained. Beginners should study this method well.
Implementation 2
The Code is as follows:
Var getRandomColor = function (){
Return (function (m, s, c ){
Return (c? Arguments. callee (m, s, C-1): '#') +
S [m. floor (m. random () * 16)]
}) (Math, '0123456789abcdef ', 5)
}
Extract the string that generates the hex color value from the Math object, and use the third parameter to determine whether to continue calling itself.
Implementation 3
The Code is as follows:
Reference content is as follows:
Array. prototype. map = function (fn, thisObj ){
Var scope = thisObj | window;
Var a = [];
For (var I = 0, j = this. length; I <j; ++ I ){
A. push (fn. call (scope, this [I], I, this ));
}
Return;
};
Var getRandomColor = function (){
Return '#' + '0123456789abcdef '. split (''). map (function (v, I, ){
Return I> 5? Null: a [Math. floor (Math. random () * 16)]}). join ('');
}
This requires us to extend the array. map will return an array, and then we use join to concatenate its elements into characters.
Implementation 4
The Code is as follows:
Reference content is as follows:
Var getRandomColor = function (){
Return '#' + Math. floor (Math. random () * 16777215). toString (16 );
}
This implementation is very backward, although a little bug. We know that the hex color value ranges from #000000 to # ffffff, And the next six digits are hexadecimal values, which are equivalent to "0x000000" to "0xffffff ". The idea of this implementation is to convert the maximum ffffff of hex into a 10-digit system first, and then convert it back to a 16-digit system after random. Let's take a look at how to get the value 16777215.
The Code is as follows:
Reference content is as follows:
Maximum Value of hex