发布于 5年前

js 数组中随机取固定值

/**
 * 数组中随机取固定值
 * arr      目标数组
 * count    数量
 */
function getRandomArrayElements(arr, count) {
  let shuffled = arr.slice(0),
    i = arr.length,
    min = i - count,
    temp,
    index;
  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random());
    temp = shuffled[index];
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }
  return shuffled.slice(min);
}
©2020 edoou.com   京ICP备16001874号-3