在 chalk.js 中获取 forEach() 内的随机颜色

Get random color inside forEach() in chalk.js

我是运行一个forEach()循环,我需要console.log()。但我想为每次迭代获得不同的颜色。我浏览了文档,但找不到任何东西。有什么办法可以达到同样的目的吗?

let arr = ["a", "ab, "abc"]
arr.forEach(arr, e => {
  console.log(chalk.red(e)) //maybe something like - chalk.randColor()
})

您可以定义一个字符串数组(所有支持的颜色)

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);

您可以尝试这样的操作:

// 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))
})

这两个函数随机提供了更大范围的不同颜色:

// 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)));

您可以使用 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'));
});

如果使用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>