0

我正在运行一个forEach()循环,我需要console.log(). 但我想为每次迭代获得不同的颜色。我浏览了文档,但找不到任何东西。有没有办法实现同样的目标?

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

5 回答 5

2

你可以尝试这样的事情:

// 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-22T08:16:04.020 回答
1

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

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-22T08:15:01.503 回答
0

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

于 2020-02-22T09:01:05.167 回答
0

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

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

于 2020-02-22T08:24:07.250 回答
0

如果您使用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>
于 2020-02-22T15:16:27.140 回答