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

时间:2014-12-04 10:55:54

标签: javascript

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

this.stepSize = random(1,30) ;

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

this.color
#f7f2ea,  #f4f4f4 , #ede0ce

我怎么能这样做?

4 个答案:

答案 0 :(得分:3)

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

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

this.color = colorArray[index];

答案 1 :(得分:2)

一种不同的方法

function randomChoice() {
    return arguments[Math.random() * arguments.length | 0];
}

this.color = '#' + randomChoice('f7f2ea', 'f4f4f4', 'ede0ce');

答案 2 :(得分:1)

试试这个方法:

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

答案 3 :(得分:0)

试试这个:

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