[英]Node.js Javascript random color print
Im trying to use the colors javascript module https://github.com/Marak/colors.js 我正在尝试使用颜色javascript模块https://github.com/Marak/colors.js
to print a random color in terminal using node.js. 使用node.js在终端中打印随机颜色。 The random generator works, but something with the period messes up the syntax and will not print the color correctly.
随机生成器可以工作,但是带有句点的东西会使语法混乱,并且不能正确打印颜色。
var colors = require('colors');
Array.prototype.random = function (length) {
return this[Math.floor((Math.random()*length))];
}
var color = ['.yellow', '.cyan', '.magenta', '.red', '.green', '.blue', '.rainbow', '.zebra']
var rcolor = color.random(color.length)
console.log(rcolor + 'rcolor')
You need to change your code a little bit 您需要稍微更改一下代码
var colors = require('colors');
Array.prototype.random = function (length) {
return this[Math.floor((Math.random()*length))];
}
var color = ['yellow', 'cyan', 'magenta', 'red', 'green', 'blue', 'rainbow', 'zebra']
var rcolor = color.random(color.length)
console.log(("Print in color " + rcolor)[rcolor]);
This is because colors add prototypes to the String class, so in JavaScript you can always execute a property method on a object using [], if can use use it in every string like this: 这是因为颜色将原型添加到String类,因此在JavaScript中,您始终可以使用[]在对象上执行属性方法,如果可以在每个字符串中都使用它,例如:
console.log("Hello colors!"[rColor]);
First, remove all of the periods. 首先,删除所有期间。 Then you should be able to do something like this:
然后,您应该可以执行以下操作:
console.log(colors[randomColor]("Hello, world!"));
Or alternatively: 或者:
console.log("Hello, world!"[randomColor]);
This works because ab
is equivalent to a["b"]
, except in the latter, you could replace "b"
with an expression. 之所以有效,是因为
ab
等效于a["b"]
,但在后者中,可以用表达式替换"b"
。 Since the colors module supports, say, colors.red(someString)
and someString.red
, we can simple change it to use the []
syntax and put in a variable there. 由于colors模块支持
colors.red(someString)
和someString.red
,我们可以简单地将其更改为使用[]
语法,然后在其中放置一个变量。
The following code (not far off what you have) prints a random color from the given list. 以下代码(相距不远)从给定列表中打印随机颜色。
var colors = require("colors");
Array.prototype.random = function () {
return this[Math.floor(Math.random() * this.length)];
};
var colorsList = [".yellow", ".red", ".blue"];
var rColor = colorsList.random();
console.log(colorsList);
console.log(rColor);
It includes colors@0.6.0-1
, but I don't know why you need it for what you have written. 它包括
colors@0.6.0-1
,但是我不知道为什么要用它来写东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.