首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在chalk.js的forEach()中获取随机颜色

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

Stack Overflow用户
提问于 2020-02-22 15:34:00
回答 5查看 656关注 0票数 0

我正在运行一个forEach()循环,并且我需要console.log()。但我希望每次迭代都有不同的颜色。我去看了医生,但什么也没找到。有没有可能实现同样的目标?

代码语言:javascript
运行
复制
let arr = ["a", "ab, "abc"]
arr.forEach(arr, e => {
  console.log(chalk.red(e)) //maybe something like - chalk.randColor()
})
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2020-02-22 16:16:04

您可以尝试如下所示:

代码语言:javascript
运行
复制
// 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))
})
票数 2
EN

Stack Overflow用户

发布于 2020-02-22 16:15:02

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

代码语言:javascript
运行
复制
const colors = ['red', 'blue', 'green'];

然后在每次迭代中随机获取颜色并使用chalk[color]

代码语言:javascript
运行
复制
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);
票数 1
EN

Stack Overflow用户

发布于 2020-02-22 16:24:07

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

代码语言:javascript
运行
复制
// 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)));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60350038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档