Javascript 使用Math.random获得相同的值

Javascript 使用Math.random获得相同的值,javascript,function,Javascript,Function,在下面的代码中,我希望功能2更改文本中的文本以完成循环。不幸的是,varrand不会将text更改为另一个单词。相反,它将始终保持不变 var x = 0; function function1() { document.getElementById("text").textContent = rand; } function function2() { if (document.getElementById("text").innerHTML === "Red") {

在下面的代码中,我希望
功能2
更改
文本中的文本以完成循环。不幸的是,var
rand
不会将
text
更改为另一个单词。相反,它将始终保持不变

var x = 0;

function function1() {
    document.getElementById("text").textContent = rand;
}

function function2() {
    if (document.getElementById("text").innerHTML === "Red") {
        x += 1;
        document.getElementById("text2").textContent = x;
        function1();
    }
}

//I have got the equivalent functions for blue, green and gold as well   
var randomarray = ['Red', 'Blue', 'Green', 'Gold', ];
var rand = randomarray[Math.floor(Math.random() * randomarray.length)];

有人能告诉我如何解决这个问题吗。

将rand声明移到函数1中。它确实选择了这种方式 a每次调用函数1时,都会再次显示颜色

function function1() {
var rand = randomarray[Math.floor(Math.random() * randomarray.length)];
document.getElementById("text").textContent = rand;
}
并注释掉(或删除)两个函数之外的声明,因为它变得无关

//var rand = randomarray[Math.floor(Math.random() * randomarray.length)];

我不清楚你在问什么:这些句子在语法上没有多大意义。请重新表述你的问题。好吧,你永远不会改变
rand
。你设定一次,就这样。如果您想更改
rand
,您必须更改它。与初始化它的方式相同
rand=randomarray[Math.floor(Math.random()*randomarray.length)]@ZAZLEO我没有说这不起作用,我只是想得到一些高质量的答案,所以…@Joaquino有些问题真的不需要/不值得太多解释。这样的案例很多。话虽如此,我确实赞同你的观点,并补充了一点简短的评论。谢谢。@MASL如果OP不知道怎么做,让他/她明白他/她在做什么的最好方法就是解释一下。否则,它可能只是一些复制和粘贴,没有获得知识。。附言:谢谢你的编辑:)@joaqínO我之前已经明白了。相信我。但说到教学,这里并没有绝对性。有时,一个具有挑战性的答案可能比一个详细的解释更具启发性。当然,知道平衡两者是一门艺术。但我不会声称自己掌握了这一点。