我正在运行一个forEach()
循环,我需要console.log()
. 但我想为每次迭代获得不同的颜色。我浏览了文档,但找不到任何东西。有没有办法实现同样的目标?
let arr = ["a", "ab, "abc"]
arr.forEach(arr, e => {
console.log(chalk.red(e)) //maybe something like - chalk.randColor()
})
我正在运行一个forEach()
循环,我需要console.log()
. 但我想为每次迭代获得不同的颜色。我浏览了文档,但找不到任何东西。有没有办法实现同样的目标?
let arr = ["a", "ab, "abc"]
arr.forEach(arr, e => {
console.log(chalk.red(e)) //maybe something like - chalk.randColor()
})
你可以尝试这样的事情:
// Create an array of possible colors
const color = ['red', 'green', 'blue', 'magenta', 'cyan', 'gray'];
let arr = ["a", "ab", "abc"]
arr.forEach(arr, e => {
// and get a random color name from the array
// and call the function on it
console.log(chalk[color[Math.floor(Math.random() * color.length)]](e))
})
您可以定义一个字符串数组(所有支持的颜色)
const colors = ['red', 'blue', 'green'];
然后在每次迭代中获取随机颜色并使用chalk[color]
let arr = ["a", "ab", "abc"];
const getRandomColor = (str) => {
const colors = ["red", "blue", "green"];
console.log(chalk[colors[Math.floor(Math.random() * colors.length)]](str));
};
arr.forEach(getRandomColor);
您可以使用chalk.rgb
随机化器值来为您提供所有级别的组合颜色。
let arr = ["a", "ab", "abc"]
const rdClr = () => Math.floor(Math.random() * 255);
const randomClor = str => chalk.rgb(rdClr(), rdClr(), rdClr())(str);
arr.forEach(arr, e => {
console.log(randomClor(arr + '%s'));
});
这两个函数随机提供更大范围的不同颜色:
// Using chalk.hex()
const randColorHex = (msg) => {
chalk.hex('#' + (Math.random() * 0xFFFFFF << 0).toString(16))(msg);
}
// Using chalk.rgb()
const randColorRgb = (msg) => {
const rand = () => Math.floor(Math.random() * 255);
chalk.rgb(rand(), rand(), rand())(msg);
}
// Usage
let arr = ["a", "ab", "abc"];
arr.forEach(item => console.log(randColorHex(item)));
arr.forEach(item => console.log(randColorRgb(item)));
如果您使用randojs.com,随机性可以更简单且更具可读性,如下所示:
var array = ["a", "ab", "abc"], colors = ['red', 'green', 'blue', 'magenta', 'cyan', 'gray'];
array.forEach((item, i) => console.log(chalk[rando(colors).value](i)));
如果要使用此代码,只需确保它位于 html 文档的 head 标记中:
<script src="https://randojs.com/1.0.0.js"></script>