3 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
嘗試以下無(wú)損(快速)功能:
function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
僅兩行:
// Shuffle array
const shuffled = array.sort(() => 0.5 - Math.random());
// Get sub-array of first n elements after shuffled
let selected = shuffled.slice(0, n);

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
創(chuàng)建一個(gè)可以做到這一點(diǎn)的功能:
var getMeRandomElements = function(sourceArray, neededElements) {
var result = [];
for (var i = 0; i < neededElements; i++) {
result.push(sourceArray[Math.floor(Math.random()*sourceArray.length)]);
}
return result;
}
您還應(yīng)該檢查sourceArray是否有足夠的元素要返回。如果要返回唯一元素,則應(yīng)從sourceArray中刪除選定的元素。
添加回答
舉報(bào)