从 3 个值中随机设置一个变量 - JavaScript

randomly set a variable from 3 values - javascript

本文关键字:一个 变量 JavaScript 设置 随机      更新时间:2023-09-26

我有以下内容,它将stepSize变量设置为1到30之间的随机数:

this.stepSize = random(1,30) ;

我想将另一个变量 (this.color) 设置为 3 个选项之间的随机值:

this.color
#f7f2ea,  #f4f4f4 , #ede0ce

我该怎么做?

将您想要的颜色放在数组中,然后随机索引

var index= Math.floor(Math.random() * 3);
var colorArray = ["f7f2ea","f4f4f4","ede0ce"];
this.color = colorArray[index];

不同的方法

function randomChoice() {
    return arguments[Math.random() * arguments.length | 0];
}
this.color = '#' + randomChoice('f7f2ea', 'f4f4f4', 'ede0ce');

试试这个方法:

this.color = ["#f7f2ea",  "#f4f4f4" , "#ede0ce"];
var randValue = Math.floor(Math.random() * 3);
console.log(this.color[randValue])

试试这个:

var rand = Math.floor(Math.random() * 3);
if(rand==0)
    this.color = "f7f2ea";
else if(rand==1)
    this.color = "f4f4f4";
else if(rand==2)
    this.color = "ede0ce";