首頁 > web前端 > js教程 > JavaScript 陣列方法,底層原理(部分)

JavaScript 陣列方法,底層原理(部分)

Linda Hamilton
發布: 2025-01-22 02:29:09
原創
598 人瀏覽過

JavaScript Array Methods, Under the Hood (Part )

本文透過使用 .map() 循環重新建立常見的 JavaScript 陣列方法 - .includes().concat().flat()for 來揭秘它們的功能。雖然 for 循環可能看起來效率較低且難以閱讀,但了解其底層機制可以讓您對內建陣列方法有更深入的了解。讓我們潛入吧!


.map()

.map() 方法透過將函數應用於現有數組的每個元素來產生新數組。 它僅處理非空元素並保持原始數組不變。

考慮一個銀行應用程式需要來自資料結構的客戶名稱清單。 雖然 .map() 是最有效的解決方案,但讓我們看看如何透過 for 循環來實現此目的:

const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 0.0 },
  { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];

// Using a 'for' loop:
function getAllClientNamesLoop(array) {
  const acctNames = [];
  for (const acct of array) {
    acctNames.push(acct.name);
  }
  return acctNames;
}

// Using .map():
function getAllClientNamesMap(array) {
  return array.map(acct => acct.name);
}

console.log(getAllClientNamesLoop(bankAccounts)); // Output: ['Susan', 'Morgan', 'Joshua', 'Candy', 'Phil']
console.log(getAllClientNamesMap(bankAccounts)); // Output: ['Susan', 'Morgan', 'Joshua', 'Candy', 'Phil']
登入後複製

for 循環方法需要建立一個空數組並迭代推送名稱。 .map() 方法明顯更簡潔可讀。

.includes()

此方法檢查陣列是否包含特定值,傳回truefalse

讓我們建立一個函數來使用 for 循環和 .includes():

來示範這一點
// Using a 'for' loop:
function doesArrayIncludeLoop(array, value) {
  let isIncluded = false;
  for (const elem of array) {
    if (elem === value) {
      isIncluded = true;
      break; // Optimization: Exit loop once value is found
    }
  }
  return isIncluded;
}

// Using .includes():
function doesArrayIncludeIncludes(array, value) {
  return array.includes(value);
}

console.log(doesArrayIncludeLoop([1, 1, 2, 3, 5], 6)); // Output: false
console.log(doesArrayIncludeIncludes([1, 1, 2, 3, 5], 3)); // Output: true
登入後複製

for 循環版本初始化一個標誌並進行迭代,而 .includes() 提供了直接且更乾淨的解決方案。

.concat()

此方法將兩個或多個數字組合併為一個新數組。

這是使用 for 循環和 .concat() 的比較:

// Using 'for' loops:
function concatArraysLoop(arr1, arr2) {
  const concatenatedArray = [...arr1, ...arr2]; //Spread syntax for conciseness
  return concatenatedArray;
}

// Using .concat():
function concatArraysConcat(arr1, arr2) {
  return arr1.concat(arr2);
}

console.log(concatArraysLoop([0, 1, 2], [5, 6, 7])); // Output: [0, 1, 2, 5, 6, 7]
console.log(concatArraysConcat([0, 1, 2], [5, 6, 7])); // Output: [0, 1, 2, 5, 6, 7]
登入後複製

再一次,.concat() 提供了卓越的簡潔性和可讀性。

.flat()

.flat() 方法將巢狀數組展平為單層數組。 它接受一個可選的深度參數。

讓我們用這兩種方法將陣列展平一層:

// Using 'for' loops:
function flatArraysLoop(array) {
  const flattenedArray = [];
  for (const elem of array) {
    if (Array.isArray(elem)) {
      flattenedArray.push(...elem); //Spread syntax
    } else {
      flattenedArray.push(elem);
    }
  }
  return flattenedArray;
}

// Using .flat():
function flatArraysFlat(array) {
  return array.flat();
}

console.log(flatArraysLoop([1, 2, 3, [4, [5, 6]], 10])); // Output: [1, 2, 3, 4, [5, 6], 10]
console.log(flatArraysFlat([1, 2, 3, [4, [5, 6]], 10])); // Output: [1, 2, 3, 4, [5, 6], 10]
登入後複製

使用 for 循環展平更深的巢狀數組變得越來越複雜,突顯了 .flat(depth) 的強大功能和簡單性。


這個探索展示了 JavaScript 內建陣列方法的優雅和高效。 第二部分將深入研究更多數組方法。 請隨意分享您的想法和問題! (第二部分的連結將在此處)

以上是JavaScript 陣列方法,底層原理(部分)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

上一篇:在 HTML 中使用
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板