在If和else语句中具有不同值的两个相同变量

时间:2015-10-28 17:09:57

标签: javascript

我应该将还原还原更改为 payback1 payback2 吗?或者有更好的方法吗?

function play() {
    var bet = document.getElementById("bet").value;
    var pips = Math.round((Math.random()*5)+1);

    if(pips == 1|| pips == 3 || pips == 5){
      document.getElementById("answer").innerHTML = "No pay";
    }
    else if(pips == 2|| pips == 4) {
      var payback = 1.25*bet;
      document.getElementById("answer").innerHTML = "You'll receive: "+payback;

    }
    else {
      var payback = 1.50*bet;
      document.getElementById("answer").innerHTML = "You'll receive: "+payback;
    }
}

第15行:'回报'已定义。

我认真地尝试了一个明智的标题......

3 个答案:

答案 0 :(得分:2)

您可以在开头声明它,然后在if / else:

上修改它
function play() {
var bet = document.getElementById("bet").value;
var pips = Math.round((Math.random()*5)+1);
var payback;

if(pips == 1|| pips == 3 || pips == 5){
  document.getElementById("answer").innerHTML = "No pay";
}
else if(pips == 2|| pips == 4) {
  payback = 1.25*bet;
  document.getElementById("answer").innerHTML = "You'll receive: "+bet;

}
else {
  payback = 1.50*bet;
  document.getElementById("answer").innerHTML = "You'll receive: "+bet;
}

}

答案 1 :(得分:1)

除了声明问题之外,为您的投注计划获得非正常分配是否可爱?您的16与其他数字的机会不同。这个机会只有其余部分的1/2。

请参阅您的案例中的分布以及一些更好的分布式值。

var i, count = {}, v;
for (i = 0; i < 12000; i++) {			
    v = Math.round((Math.random() * 5) + 1);
    count[v] = (count[v] || 0) + 1;
}
document.write('<pre>' + JSON.stringify(count, 0, 4) + '</pre>');
count = {};
for (i = 0; i < 12000; i++) {			
    v = Math.floor((Math.random() * 6) + 1);
    count[v] = (count[v] || 0) + 1;
}
document.write('<pre>' + JSON.stringify(count, 0, 4) + '</pre>');

答案 2 :(得分:0)

你应该能够内联并跳过变量声明:

document.getElementById("answer").innerHTML = "You'll receive: "+(1.25*bet);