美文网首页
js 从数组中获取不同的随机元素

js 从数组中获取不同的随机元素

作者: 我讲你思 | 来源:发表于2019-04-16 19:16 被阅读0次
let arr = [1,2,3,4,5,6,7,8,9]
function getRandom(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);
}

console.log(getRandom(arr, 4))

相关文章

网友评论

      本文标题:js 从数组中获取不同的随机元素

      本文链接:https://www.haomeiwen.com/subject/bnsiwqtx.html