在JavaScript中使用数组获取随机十六进制

在JavaScript中使用数组获取随机十六进制,javascript,arrays,random,colors,hex,Javascript,Arrays,Random,Colors,Hex,我写了一个生成随机颜色的小代码。它基于从0到9以及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()

我写了一个生成随机颜色的小代码。它基于从0到9以及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>
我知道它给了我一个数组“强度”中的随机元素,但我不知道它是如何工作的。有人能给我解释一下吗?提前谢谢。

使用
Math.random()
可以得到一个介于0和1之间的数字(float)(但不是安德烈亚斯指出的1)

如果你想要一个从0到X的数字,你必须乘以X
Math.random()*X

强度指数从
0
intensity.length

这就是为什么需要
Math.random()*intensity.length
来随机获取强度索引

由于乘法的结果是一个浮点数,您可以使用floor去除小数,此时您有:
Math.floor(Math.random()*intensity.length)

这是要获得的强度的随机指数:

intensity[Math.floor(Math.random() * intensity.length)]

您可以在网上找到许多随机十六进制颜色生成器的示例,例如:


生成范围内随机数的基础知识`var x=Math.floor(Math.random()*intensity.length);var color=intensity[x]这太复杂了,看。这能回答你的问题吗?“Math.random()函数返回一个0到小于1的浮点伪随机数(不包括0,但不是1)”cero在9之后,我忘了在开始时写它,所以我在9之后写它。好了,现在我明白多了。我已经做了测试,现在我得到了语法方面的一切。谢谢你,我知道我能找到很多例子。颜色上的东西只是一个借口,可以得到关于Math.floor和Math.random如何工作的正确解释。基本上
Math.random()
生成一个介于0和1之间的随机数,类似于0.12345。要获得介于0和n之间的随机数,您可以使用
Math.random()
生成一个随机数,然后乘以n。结果类似于123.45,因此您可以使用
Math.foor
再次将其转换回integerthanks。现在我正在尝试理解颜色的函数。。。我在谷歌上搜索:)明白了!十六进制和16777215的值与颜色和十六进制有关。。。我现在没有。是的,十进制的16777215被转换成十六进制的FFFFFF,这恰好是十六进制颜色的最大值
intensity[Math.floor(Math.random() * intensity.length)]
function randomHexColor() {
  return Math.floor(Math.random()*16777215).toString(16);
}