这几天遇到了需要从数组中随机取样的需求,看别人写的很复杂,于是自己写了一个:
Array.prototype.sample = function() {
if (!this.length) return;
let rand = Math.floor(Math.random() * this.length);
return this[rand];
}
Math.floor
可以简写为 ~~
:
Array.prototype.sample = function() {
if (!this.length) return;
return this[~~(Math.random() * this.length)];
}
写个方法测试一下:
class Test {
constructor() {
this.redCount = 0;
this.greenCount = 0;
this.blueCount = 0;
}
run() {
for (let i=0; i<10000; i++) {
let res = ['red', 'green', 'blue'].sample();
switch (res) {
case 'red':
this.redCount++;
break;
case 'green':
this.greenCount++;
break;
case 'blue':
this.blueCount++;
break;
default:
break;
}
}
console.log(`red ${this.redCount}, green ${this.greenCount}, red ${this.blueCount}`);
}
}
new Test().run();
// red 3389, green 3289, red 3322
另外如果不想自己麻烦,lodash
提供了 sample
函数可以从集合中获得一个随机元素:
import _ from "lodash";
_.sample([1, 2, 3, 4]);
// 2