js实现从数组里随机获取元素

醉菜鸟 2021-12-29 09:00:02

/**
 * 获取随机数组
 * @param $array
 * @param $count
 * @returns {*}
 */
function getRandomArray($array, $count) {
  let shuffled = $array.slice(0), i = $array.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);
} 
意见反馈