我的代码有问题,我想在历史记录框中看到通过的4个生成的数字(Math.random),但这些数字显示的相同。有没有办法延迟var?
我尝试按顺序排列var,但这不会造成延迟。
我的html:
<div class="text-position-history">
<div class="text-style-history">
<p id="historyT"></p>
</div>
</div>
</body>
</html>
我的JavaScript:
var green = 0;
var red = 0;
function odds(){
var result = Math.random();
if (result < 0.5)
{
document.body.style.backgroundColor = "green";
green++;
document.getElementById('greenT').innerHTML = "Times you survived: " + " " + green;
}
else{
document.body.style.backgroundColor = "red";
red++;
document.getElementById('redT').innerHTML = "Times you died: " + " " + red;
}
document.getElementById('resultT').innerHTML = "Guessed number: " + " " + result;
var history1 = result;
var history2 = history1;
var history3 = history2;
document.getElementById('historyT').innerHTML = "Guessed number: " + " " + result + " " + history1 + " " + history2 + " " + history3;
}
有没有办法做到这一点?
答案 0 :(得分:0)
为什么不创建一个数组,然后在调用Math.random()
之后将结果的新值附加到该数组?
var resultHistory = new Array();
var result = Math.random();
resultHistory.push(result);
然后稍后打印出阵列。
答案 1 :(得分:0)
为什么不只使用数字数组?
const bus = require("./bus");
class Subscriber {
constructor(emitter) {
this.emitter = emitter;
console.log(this.emitter);
this.emitter.on("test", this.handleTest);
}
handleTest(data) {
console.log("handling test", data);
}
}
module.exports = Subscriber;
console.log(bus.instance.foo);
var _history = [];
function toHTMLElement(historyNode)
{
var node = document.createElement("div");
node.innerHTML = historyNode.text;
node.style.background = historyNode.win?'green':'red';
return node;
}
function renderHistory()
{
var result = document.getElementById("result");
result.innerHTML = "";
_history.forEach(function(e){
result.appendChild(toHTMLElement(e));
});
}
document.getElementById("form").addEventListener("submit", function(e){
e.preventDefault();
_history.push((Math.random()>0.5)?{win: true, text: 'You win'}:{win: false, text: 'You lose'});
if (_history.length > 3) _history.shift();
renderHistory();
});
答案 2 :(得分:0)
var green = 0;
var red = 0;
function odds(){
var result = Math.random();
if (result < 0.5)
{
document.body.style.backgroundColor = "green";
green++;
document.getElementById('greenT').innerHTML = "Times you survived: " + " " + green;
}
else{
document.body.style.backgroundColor = "red";
red++;
document.getElementById('redT').innerHTML = "Times you died: " + " " + red;
}
document.getElementById('resultT').innerHTML = "Guessed number: " + " " + result;
var myList = [result, result, result];
var history1 = myList.shift();
var history2 = myList.shift();
var history3 = myList.shift();
document.getElementById('historyT').innerHTML = "Guessed numbesr: " + " " + history1 + " " + history2 + " " + history3;
}
这仍然给出相同的结果吗?
答案 3 :(得分:-1)
我认为实际上更改历史记录变量的顺序应该可以解决。 将它们更改为
var history3 = history2;
var history2 = history1;
var history1 = result;
现在,您对所有结果都一无所知,原因是:
var history1 =结果 var history2 = history1(history1现在已指向结果)