sampleSize
2024年06月17日
一、认识
从 collection
(集合)中获得 n
个随机元素。
二、语法
三、实现
function sampleSize(array, n) {
let nCopy = n == null ? 1 : n;
const length = array == null ? 0 : array.length;
if (length == 0 || nCopy < 1) {
return [];
}
nCopy = nCopy > length ? length : n;
let index = -1;
const lastIndex = length - 1;
const result = [...array];
while (++index < nCopy) {
const rand = index + Math.floor(Math.random() * (lastIndex - index + 1));
const value = result[rand];
result[rand] = result[index];
result[index] = value;
}
return result.slice(0, n);
}
console.log(sampleSize([1, 2, 3], 1));