【问题标题】:Button that has 1.04% chance to lead to Page A and 98.96% chance to lead to Page B? -JavaScript按钮有 1.04% 的机会引导到页面 A 和 98.96% 的机会引导到页面 B? -JavaScript
【发布时间】:2020-05-08 19:11:15
【问题描述】:

我正在尝试创建一个按钮,按下该按钮时有 1.04% 的机会导致页面 A 和 98.96% 的机会导致页面 B。这是我的总体目标,但我遇到问题的具体方面是结果的随机化。我对javascript很陌生,所以我提前道歉。任何帮助表示赞赏。

--编辑-- 我正在将此代码合并到一个 Wix 项目中,这是我到目前为止的全部代码。我从简单的整数 40/60 开始,以确保我能做到,但较小的百分比我很难合并。重要的是我的小数百分比是 1.04 而不是 1.00。

import wixLocation from 'wix-location';
let random = 0,counter40 = 0,counter60 = 0;

$w.onReady(function () {
 for (var i = 0; i < 10000000; i++) {
    random = Math.floor((Math.random() * 100) + 1);
    if (random <= 40)   {
        counter40++;
    } else {
        counter60++;
     }
  }
  console.log("counter40: " + counter40.toString());
  console.log("counter60: " + counter60.toString());
});

export function button1_click(event) {
    random = Math.floor((Math.random() * 100) + 1);
    if (random <= 40)   {
        wixLocation.to("/pageB");
    } else {
        wixLocation.to("/pageC");
   }
}

【问题讨论】:

  • 您尝试过什么解决问题的方法?
  • 好吧,我将这方面整合到一个 wix 网站中(这是另一回事),但我已经用我目前拥有的代码更新了我的问题

标签: javascript arrays button


【解决方案1】:

https://jsfiddle.net/ys84pu6a/1/

HTML:

<button id="randomRedirect">
  Press me
</button>

JS:

let button = document.getElementById('randomRedirect')
button.addEventListener('click', function() {
  let d = Math.random();
  if (d < 0.9896)
    window.location.href = "pageB.html";
  else
    window.location.href = "pageA.html";
}, false);

【讨论】:

    【解决方案2】:

    使用Math.random() 函数。它返回一个介于 0 和 1 之间的随机数。 你可以这样使用它:

    x = Math.random()
    if(x < 0.0104){//1.04% chance
      window.location.href = [Page A]
    }
    else{
      window.location.href = [Page B]
    }

    【讨论】:

    • 我们通常不会回答未向site guidelines 确认的糟糕问题(即未尝试制定和发布解决方案)。
    【解决方案3】:

    提供伪随机值的函数是Math.random()

    它返回一个介于 0 和 1 之间的浮点数。

    要获得 1.04% 的机会,您只需这样做:

    let pageAChance = Math.random() <= 0.0104;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 2021-02-11
      • 2017-05-22
      相关资源
      最近更新 更多