我们需要编写一个返回随机十六进制颜色的函数。所以这是这样做的代码-
const generateRandomColor = () => { const keys = '0123456789ABCDEF'; let color = ''; while(color.length < 6){ const random = Math.floor(Math.random() * 16); color += keys[random]; }; return `#${color}`; }; console.log(generateRandomColor()); console.log(generateRandomColor()); console.log(generateRandomColor()); console.log(generateRandomColor());
输出结果
控制台中的输出将为-
#C83343 #D9AAF3 #9D55CC #28AE22