數組的隨機抽取...

operateArray.js

// 目標數組中 隨機抽取 新數組
export const getRandomArray = function (arr, num) {
  let out = []
  let n = arr.length > num ? num : arr.length
  while (out.length < n) {
    let temp = parseInt(Math.random() * arr.length)
    out = [...out, ...arr.splice(temp, 1)]
  }
  return out
}
複製代碼

使用

import { getRandomArray } from '../utils/operateArray'

getRandomArray([1,2,3,4,5], 3) // [4, 1, 2]
複製代碼
相關文章
相關標籤/搜索