[英]How to use math.random again to get a different value if the values are the same in javascript
[英]Get same values with Math.random
在下面的代碼中,我想function 2
更改文本中的text
以完成循環。 不幸的是,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的聲明移到function1內部。 這樣,每次調用function1時,它的確選擇了一種顏色
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)];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.