I have written a little code that generates a random color. It is based in an array that goes from 0 to 9 and A,B,C,D,E,F:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Ejercicio 7</title>
<script type="text/javascript">
function changeColor() {
const intensity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "A", "B", "C", "D", "E", "F"];
let randomColor1 = intensity[Math.floor(Math.random() * intensity.length)];
let randomColor2 = intensity[Math.floor(Math.random() * intensity.length)];
let randomColor3 = intensity[Math.floor(Math.random() * intensity.length)];
let randomColor4 = intensity[Math.floor(Math.random() * intensity.length)];
let randomColor5 = intensity[Math.floor(Math.random() * intensity.length)];
let randomColor6 = intensity[Math.floor(Math.random() * intensity.length)];
const randomColor = `#${randomColor1}${randomColor2}${randomColor3}${randomColor4}${randomColor5}${randomColor6}`;
document.body.style.backgroundColor = randomColor;
}
</script>
</head>
<body onload="changeColor()">
<button onclick="changeColor()">Pincha aquí</button>
</body>
</html>
The problem is I don't understand this piece of repeated code:
intensity[Math.floor(Math.random() * intensity.length)]
I know it gives me a random element from the array "intensity", but I don't know how it works. Can someone explain to me? Thank you in advance.
Aucun commentaire:
Enregistrer un commentaire