如何为jQuery函数提供50/50的概率?

时间:2016-11-02 07:22:53

标签: javascript jquery html function probability

我有这个功能:

$(document).on("click",".battleOne",function() {

});

我希望函数中出现两个事件之一的概率为50%:

事件#1:

coins += 5;
alert("Your dog won the battle!\n+ 5 coins");

事件#2:

coins -= 1;
alert("Your dog died in battle :(\n- 5 coins");

基本上我想要:

$(document).on("click",".battleOne",function() {

//50% chance of this happening:
coins += 5;
alert("Your dog won the battle!\n+ 5 coins");

//50% chance of this happening:
coins -= 1;
alert("Your dog died in battle :(\n- 5 coins");

});

提前致谢!

3 个答案:

答案 0 :(得分:4)

您可以使用Math.random()方法。它返回0到1之间的随机值。这是一个简单的例子:

$(document).on("click",".battleOne",function() {
    if(Math.random() < 0.5) {
        coins += 5;
        alert("Your dog won the battle!\n+ 5 coins");
    } else {
        coins -= 5;
        alert("Your dog died in battle :(\n- 5 coins");
    }
});

显然,coins需要是函数范围内可访问的某种全局变量。

答案 1 :(得分:1)

在0和1之间使用random number,测试数字是否大于0.5或更小,这将给你50-50%

   var coins;
$(document).on("click", ".battleOne", function() {
      var number = Math.random();
      if (number < 0.5) {
        coins += 5;
        alert("Your dog won the battle!\n+ 5 coins");
      } else {

        coins -= 1;
        alert("Your dog died in battle :(\n- 5 coins");
      }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="battleOne">battleOne</button>

如果您想要不同的值40-60只需将条件更改为0.4或0.6,具体取决于您想要的更好%

答案 2 :(得分:0)

借助Math.random

尝试此操作
var coins = 0;
$(document).on("click", ".battleOne", function() {
    var rand = Math.round(Math.random() * 1); // generates an int of 0 or 1
    if (rand) {
        coins += 5;
        alert("Your dog won the battle!\n+ 5 coins");
    } else {
        coins -= 1;
        alert("Your dog died in battle :(\n- 1 coins");
    }
    console.log(coins);
});