我正在运行一个forEach()
循环,并且我需要console.log()
。但我希望每次迭代都有不同的颜色。我去看了医生,但什么也没找到。有没有可能实现同样的目标?
let arr = ["a", "ab, "abc"]
arr.forEach(arr, e => {
console.log(chalk.red(e)) //maybe something like - chalk.randColor()
})
发布于 2020-02-22 16:16:04
您可以尝试如下所示:
// 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))
})
发布于 2020-02-22 16:15:02
您可以定义字符串数组(所有支持的颜色)
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);
发布于 2020-02-22 16:24:07
这两个函数随机提供更大范围的不同颜色:
// 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)));
https://stackoverflow.com/questions/60350038
复制相似问题