欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript數(shù)組合并的7種高效方法詳解

 更新時間:2025年08月08日 11:35:55   作者:編程隨想?  
這篇文章主要介紹了在日常?JavaScript?開發(fā)中,數(shù)組操作是最常見的任務(wù)之一,其中數(shù)組合并更是高頻需求,本文給大家介紹了JavaScript數(shù)組合并的7種高效方法,并通過代碼示例講解的非常詳細,需要的朋友可以參考下

一、為什么需要數(shù)組合并?

在數(shù)據(jù)處理中,我們經(jīng)常需要:

  • 合并多個 API 返回的數(shù)據(jù)集
  • 組合不同來源的用戶輸入
  • 扁平化嵌套數(shù)據(jù)結(jié)構(gòu)
  • 匯總計算結(jié)果

掌握高效合并方法能大幅提升代碼質(zhì)量和性能!

二、7 種數(shù)組合并方法詳解

1. concat() - 經(jīng)典合并方法

const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];

// 合并兩個數(shù)組
const merged = arr1.concat(arr2); 
// [1, 2, 3, 4]

// 合并多個數(shù)組
const allMerged = arr1.concat(arr2, arr3);
// [1, 2, 3, 4, 5, 6]

特點

  • ? 不改變原數(shù)組
  • ? 可合并多個數(shù)組
  • ? 不支持深層次嵌套數(shù)組的扁平化

2. 擴展運算符(ES6 首選) 

const fruits = ['??', '??'];
const veggies = ['??', '??'];
const sweets = ['??', '??'];

// 基礎(chǔ)合并
const healthyFood = [...fruits, ...veggies];
// ['??', '??', '??', '??']

// 多數(shù)組合并
const allFood = [...fruits, ...veggies, ...sweets];
// ['??', '??', '??', '??', '??', '??']

// 插入元素
const withIceCream = [...fruits, '??', ...sweets];
// ['??', '??', '??', '??', '??']

特點

  • ? 語法簡潔直觀
  • ? 靈活插入額外元素
  • ? 現(xiàn)代 JS 開發(fā)首選方式
  • ? 舊瀏覽器需要 polyfill

3. push() + 擴展運算符 - 動態(tài)添加元素 

const cart = ['??', '??'];
const newItems = ['??', '?'];

// 合并到現(xiàn)有數(shù)組(改變原數(shù)組)
cart.push(...newItems);
console.log(cart); 
// ['??', '??', '??', '?']

特點

  • ? 直接修改原數(shù)組
  • ? 高效添加多個元素
  • ? 無法處理超大數(shù)組(可能棧溢出)

4. reduce() - 函數(shù)式編程利器 

const arrays = [[1, 2], [3, 4], [5, 6]];

const flattened = arrays.reduce((acc, current) => {
  return acc.concat(current);
}, []);

console.log(flattened); // [1, 2, 3, 4, 5, 6]

高級用法 - 條件合并

const data = [
  [1, 2],
  null,
  [5, 6],
  undefined,
  [7, 8]
];

const cleanMerge = data.reduce((acc, curr) => {
  return curr ? [...acc, ...curr] : acc;
}, []);

console.log(cleanMerge); // [1, 2, 5, 6, 7, 8]

特點

  • ? 處理復(fù)雜合并邏輯
  • ? 過濾無效數(shù)據(jù)
  • ? 性能不如原生方法

5. flat() - 嵌套數(shù)組克星(ES2019) 

const nestedArray = [1, [2, 3], [4, [5, 6]]];

// 默認展開一層
console.log(nestedArray.flat()); 
// [1, 2, 3, 4, [5, 6]]

// 展開所有層級
console.log(nestedArray.flat(Infinity)); 
// [1, 2, 3, 4, 5, 6]

特點

  • ? 專為嵌套數(shù)組設(shè)計
  • ? 可控制展開深度
  • ? 不兼容 IE 和舊移動瀏覽器

6. 手動循環(huán) - 最基礎(chǔ)方法 

const nums = [10, 20];
const newNums = [30, 40];

// 使用 for 循環(huán)
for (let i = 0; i < newNums.length; i++) {
  nums.push(newNums[i]);
}

// 使用 forEach
newNums.forEach(num => nums.push(num));

console.log(nums); // [10, 20, 30, 40]

特點

  • ? 最高兼容性
  • ? 完全控制合并過程
  • ? 代碼冗長

7. Array.from() + Set - 合并去重 

const dupArr1 = [1, 2, 3];
const dupArr2 = [2, 3, 4];

// 合并并去重
const uniqueMerge = Array.from(
  new Set([...dupArr1, ...dupArr2])
);

console.log(uniqueMerge); // [1, 2, 3, 4]

特點

  • ? 自動去重
  • ? 簡潔高效
  • ? 無法自定義去重邏輯

三、性能對比與最佳實踐

性能測試結(jié)果(合并 10000 個元素的數(shù)組 x 1000 次)

方法耗時(ms)內(nèi)存占用
concat()120
擴展運算符125
push + 擴展運算符110最低
reduce()350
flat()200
手動循環(huán)130

最佳實踐建議

  1. 現(xiàn)代項目:優(yōu)先使用擴展運算符([...arr1, ...arr2]
  2. 需要修改原數(shù)組:使用 arr1.push(...arr2)
  3. 深度嵌套數(shù)組:使用 flat(Infinity)
  4. 需要去重:結(jié)合 Set 和擴展運算符
  5. 超大型數(shù)組:使用循環(huán)分塊處理
  6. 兼容舊瀏覽器:使用 concat() 或手動循環(huán)

四、實戰(zhàn)應(yīng)用場景

場景 1:合并 API 分頁數(shù)據(jù)

async function fetchAllPages() {
  let allData = [];
  let page = 1;
  
  while (true) {
    const response = await fetch(`/api/data?page=${page}`);
    const data = await response.json();
    
    if (data.length === 0) break;
    
    allData = [...allData, ...data];
    page++;
  }
  
  return allData;
}

場景 2:表單多組輸入合并

function getFormData() {
  const personalInfo = ['name', 'email'];
  const preferences = ['theme', 'language'];
  const security = ['password', '2fa'];
  
  return {
    fields: [...personalInfo, ...preferences, ...security],
    // ES2020 可選鏈操作符
    timestamp: new Date().toISOString()
  };
}

場景 3:遞歸合并嵌套配置 

function mergeConfigs(defaults, custom) {
  return {
    ...defaults,
    ...custom,
    nestedOptions: {
      ...defaults.nestedOptions,
      ...custom.nestedOptions
    }
  };
}

五、總結(jié)與擴展知識

掌握數(shù)組操作是 JavaScript 開發(fā)的核心能力,本文涵蓋的 7 種合并方法各有適用場景:

  1. 簡單合并 → 擴展運算符
  2. 修改原數(shù)組 → push(...arr)
  3. 深度嵌套 → flat()
  4. 兼容性需求 → concat() 或循環(huán)
  5. 高級處理 → reduce()
  6. 合并去重 → Set + 擴展運算符

擴展知識

  • 使用 Array.isArray() 驗證輸入確保安全合并
  • 使用 lodash 的 _.flattenDeep() 處理復(fù)雜嵌套
  • 使用 flatMap() 實現(xiàn)合并+映射一步到位

以上就是JavaScript數(shù)組合并的7種高效方法詳解的詳細內(nèi)容,更多關(guān)于JavaScript數(shù)組合并方法的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論