如何将变量重置为默认值?

时间:2018-06-23 02:41:02

标签: javascript

我创建了JavaScript代码,其中有两个圆圈,如果您单击右边的圆圈,您将获得1分。我想创建一个按钮,通过将我的变量重置为0来重置游戏。

到目前为止,这是我的代码

SaveChanges()

最初,我使用了以下代码进行重置,但无法正常工作

var result = document.getElementById("result");
    var head = document.getElementById("circle");
    var tails = document.getElementById("circle2");
    var win = document.getElementById("win");
    var loss = document.getElementById("loss");
    var winsorloss = 1;
    var winsorloss2 = 1;
    var winsorloss3 =1;
     var winsorloss4 = 1;


    head.addEventListener("click", function(){
        var num = Math.random()
        if (num > .50) {

            result.innerHTML="You clicked Heads and the result was Heads You won";
            win.innerHTML= winsorloss++
        }else{
            result.innerHTML="You clicked Heads and the result was Tails You lost";
            loss.innerHTML = winsorloss2++;
        }


    })

    tails.addEventListener("click", function(){
        var num2 = Math.random()
        if (num2 < .50) {

            result.innerHTML="You clicked Tails and the result was Tails You won";
            win.innerHTML=winsorloss3 = winsorloss++
        }else{
            result.innerHTML="You clicked Tails and the result was Heads You lost";
            loss.innerHTML=winsorloss4 =winsorloss2++;
        }


    })

2 个答案:

答案 0 :(得分:1)

变量的初始值均为1,而不是0。最初起作用的原因是因为更新时使用的是后递增的,所以先用旧值更新HTML,然后再递增变量。最好将它们初始化为0并使用预增量,以便变量包含您在结果中显示的相同内容。

var result = document.getElementById("result");
var head = document.getElementById("circle");
var tails = document.getElementById("circle2");
var win = document.getElementById("win");
var loss = document.getElementById("loss");
var winsorloss = 0;
var winsorloss2 = 0;
var winsorloss3 = 0;
var winsorloss4 = 0;

head.addEventListener("click", function() {
  var num = Math.random()
  if (num > .50) {

    result.innerHTML = "You clicked Heads and the result was Heads You won";
    win.innerHTML = ++winsorloss;
  } else {
    result.innerHTML = "You clicked Heads and the result was Tails You lost";
    loss.innerHTML = ++winsorloss2;
  }
})

tails.addEventListener("click", function() {
  var num2 = Math.random()
  if (num2 < .50) {

    result.innerHTML = "You clicked Tails and the result was Tails You won";
    win.innerHTML = winsorloss3 = ++winsorloss;
  } else {
    result.innerHTML = "You clicked Tails and the result was Heads You lost";
    loss.innerHTML = winsorloss4 = ++winsorloss2;
  }
})

function reset() {
  winsorloss = winsorloss2 = winsorloss3 = winsorloss4 = 0;
  win.innerHTML = "0";
  loss.innerHTML = "0";
}

答案 1 :(得分:0)

简单例子

var default_value=()=>({
a:1,
b:2,
})

var bill=default_value();
bill.a=7;
console.log(bill)
console.log("---------------reset all value---------------")
bill=default_value();

console.log(bill)