如何编写一个可能触发的函数,给出一些概率,比如说:0 - 100?

pub*_*ide 1 javascript function

我需要一个具有某种可能性的函数,它会触发,例如:

function broken_fn ( function () { console.log( Math.random() ); }, 33 ) {
    // code...
}
Run Code Online (Sandbox Code Playgroud)

用于简单的在线游戏我正在努力...

pfr*_*ank 10

怎么样:

function maybeFire (fn, probability) {
    if (Math.random() < probability) {
         fn();
    }
}    
Run Code Online (Sandbox Code Playgroud)

用它作为:

maybeFire(function() { console.log('fired!'); }, .5);
Run Code Online (Sandbox Code Playgroud)

  • 代码什么时候"太短"?唯一的问题是它需要'0-1`而不是'0-100`但很容易调整. (7认同)