首页 > 解决方案 > 如何使用javascript根据变量的值设置随机百分比机会

问题描述

假设我有一个值为 5 的变量,变量的值越高,成功的机会就越高。

那么我怎么能做这样的事情呢?:

function mission1() {
if (user_power < 5) {
//30% change of succes
} else if (user_power == 5) {
//50% change of succes
} else if (user_power > 5) {
//80% change of succes
}

标签: javascripteventsrandom

解决方案


我不知道我是否正确理解了您想要什么,但这是我的解决方案:

  function mission1(user_power) {
    if (user_power < 5) {
      // 30% chance of succes
      return Math.random() < 0.3;
    } else if (user_power == 5) {
      //50% chance of succes
      return Math.random() < 0.5;
    } else if (user_power > 5) {
      //80% chance of succes
      return Math.random() < 0.8;
    }
  }

该函数根据给定的参数返回一个布尔值。
注意: Math.random() 返回一个介于 0 和 1 之间的浮点数,因此它低于 0.8 的可能性是 80%。


推荐阅读