如何实现一个 sample 函数,从数组中随机取一个元素
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 443 (opens in a new tab)
Author 回答者: eriksyuan (opens in a new tab)
function sample(arr){ const index = Math.floor(Math.random() * arr.length ) return arr[index] }
Author 回答者: reveriesMeng (opens in a new tab)
Array.prototype.sample = function () {
if (!Array.isArray(this)) {
throw new Error("not a Array");
}
return this[Math.floor(Math.random() * this.length)];
};
Author 回答者: 271853754 (opens in a new tab)
function random(n, m) {
var result = Math.random() * (m + 1 - n) + n;
while (result > m) {
result = Math.random() * (m + 1 - n) + n;
}
return Math.round(result);
}
Array.prototype.sample = function () {
if (!Array.isArray(this)) {
throw new Error("not a Array");
}
return this[random(0, this.length - 1)];
};
Author 回答者: shfshanyue (opens in a new tab)
Math.random() 函数返回一个浮点, 伪随机数在范围从0到小于1,用数学表示就是 [0, 1),可以利用它来实现
sample
函数
Array.prototype.sample = function () {
return this[Math.floor(Math.random() * this.length)];
};
Author 回答者: tangli06 (opens in a new tab)
Math.random() 函数返回一个浮点, 伪随机数在范围从0到小于1,用数学表示就是 [0, 1),可以利用它来实现 sample 函数 Array.prototype.sample = function() { return this[Math.floor(Math.random()*this.length)] }; @shfshanyue 调用时箭头函数this不是指向调用数组,写成普通函数有效
Author 回答者: shfshanyue (opens in a new tab)
@tangli06 大意了