萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 從數組隨機獲取不重複元素完整實現

JS 數組隨機抽樣:從基礎到高性能封裝

在抽獎、隨機推薦、測試數據生成等場景,常需從數組中隨機抽取指定數量的不重複元素。本文從基礎 API 切入,逐步構建健壯、高性能的通用函數。

基礎知識:數組複製的三種方式

const arr = [1, 5, 9, 7];

// 1. 擴展運算符(現代首選,淺拷貝)
const copy1 = [...arr];

// 2. concat() - 返回新數組
const copy2 = arr.concat();

// 3. slice() - 截取全部
const copy3 = arr.slice(0);

// ❌ 不推薦:for 循環 push,冗長且無優勢

核心邏輯:Fisher-Yates 洗牌算法變體

為避免重複抽取,採用「抽取後從副本移除」策略,時間複雜度 O(k),k 為抽取數量:

/**
 * 從數組隨機獲取指定數量不重複元素
 * @param {Array} arr - 源數組
 * @param {Number} count - 抽取數量
 * @returns {Array} 抽取結果
 */
function getRandomElements(arr, count) {
  // 參數校驗
  if (!Array.isArray(arr) || arr.length === 0) return [];
  count = Math.min(count, arr.length);
  
  // 複製數組避免污染源數據
  const pool = [...arr];
  const result = [];
  
  for (let i = 0; i < count; i++) {
    // 隨機索引 [0, pool.length)
    const randomIndex = Math.floor(Math.random() * pool.length);
    // 取出元素並從池中移除
    result.push(pool.splice(randomIndex, 1)[0]);
  }
  
  return result;
}

// 使用示例
const prizes = ["一等獎", "二等獎", "三等獎", "安慰獎", "謝謝參加"];
console.log(getRandomElements(prizes, 3)); // 如 ["三等獎", "一等獎", "安慰獎"]

進階封裝:支持選項對象

function getRandom(opt) {
  const { array, count, unique = true } = opt;
  if (!Array.isArray(array)) throw new TypeError("array 必須是數組");
  
  const pool = unique ? [...array] : array; // 非唯一模式直接用原數組
  const n = Math.min(count, pool.length);
  const result = [];
  
  for (let i = 0; i < n; i++) {
    const idx = Math.floor(Math.random() * pool.length);
    result.push(pool[idx]);
    if (unique) pool.splice(idx, 1);
  }
  return result;
}

// 使用
const winners = getRandom({ 
  array: ["張三", "李四", "王五", "趙六", "錢七"], 
  count: 2 
});

大數組優化:部分洗牌

當數組極大(如 10 萬+)但只需少量元素時,完整洗牌浪費性能。可僅洗牌前 k 個:

function getRandomLarge(arr, k) {
  const copy = [...arr];
  const n = copy.length;
  k = Math.min(k, n);
  
  for (let i = 0; i < k; i++) {
    const j = i + Math.floor(Math.random() * (n - i));
    [copy[i], copy[j]] = [copy[j], copy[i]]; // 交換
  }
  return copy.slice(0, k);
}

加密級隨機需求

若用於安全敏感場景(如密碼生成、加密抽獎),請使用 crypto.getRandomValues():

function secureRandom(arr, count) {
  const pool = [...arr];
  const result = [];
  const uint32 = new Uint32Array(1);
  
  for (let i = 0; i < count && pool.length; i++) {
    crypto.getRandomValues(uint32);
    const idx = uint32[0] % pool.length;
    result.push(pool.splice(idx, 1)[0]);
  }
  return result;
}

根據業務場景選擇合適方案:常規業務用基礎版,大數據用部分洗牌,安全敏感用加密隨機。

copyright © 萬盛學電腦網 all rights reserved