按给定几率进行随机抽取的js代码

复制代码 代码如下:

  function StringResource(k) { return StringResource[k] || k; }

  function RandomSelector() {

  var f = 0, c = [];

  return function (v, r) {

  if (arguments.length) {

  if (r <= 0) throw { message: StringResource("INVALID_ARGUMENT") };

  c.push([r, v]);

  f += r;

  } else {

  var i = 0; r = Math.random() * f;

  for (; ; ) if ((r -= (v = c[i++])[0]) < 0) return v[1];

  }

  };

  }