I have some simple code that randomly changes the background color on the page. Why do I need to use let letters = "0123456789ABCDEF".split('')
in the code?
function changeColor() {
document.body.style.backgroundColor = getRandomColor()
}
function getRandomColor() {
let color = "#";
let letters = "0123456789ABCDEF".split('');
for (let i = 0; i < 6; i ) {
color = letters[Math.floor(Math.random() * 16)];
}
return color;
}
function test() {
changeColor();
setInterval(changeColor, 1000)
}
test();
CodePudding user response:
The "0123456789ABCDEF"
string is effectively a list of all characters available in hexadecimal. The split()
call turns this in to an array, which is then randomly accessed 6 times to create a random colour in hex.
An alternative one-line method to do this would be to generate a random number between 0 and the upper limit (which for 6 hex characters is 16^6, or specifically 16,777,215) and then turn this in to a hex value using toString(16)
:
const randomHex = Math.floor(Math.random() * Math.pow(16, 6)).toString(16);
console.log(randomHex);
CodePudding user response:
A color is hexadecimal string (base 16) made of 6 character (7 include the #).
CodePudding user response:
the function is to getRandomColor, color consists of hexadecimal digits. "let letters = "0123456789ABCDEF".split('');" the expression is meant to convert a string "0123456789ABCDEF" to an array ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E']
CodePudding user response:
The split creates an array of letters so it can be crawled with the for{} loop.
The for loop then creates and concatenes a 6 characters string by taking a random value from the letters table (a random character in the ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] set).
The Math.floor(Math.random() * 16) code gives you a number between 1 and 16 (one of the random 16 keys in the letters table) because Math.random() outputs for example :
- rand gives you 0.6705686567474212
- rand * 16 : 10.729098507958739
- floored : 10
- letters[10] = 9
So your first loop gives you #9
Loop it 5 more times and you get #9536AF