JavaScript >> Javascript 文檔 >  >> Tags >> Arrays

如何比較 JavaScript 中的數組,並附上示例

本文將向您展示如何在 JavaScript 中比較數組,並提供一些現成的函數。

我們已經介紹了一些關於如何在 JavaScript 中使用數組:

  • 使用 JavaScript forEach() 循環遍歷數組,並附上示例
  • JavaScript 中的數組 slice() 方法,帶有 Examples()
  • 用示例檢查數組是否包含 JavaScript 中的值
  • 使用示例從 JavaScript 中的數組中刪除元素

什麼是數組?

數組是一種 JavaScript 變量,可以在列表中的某個位置保存其他變量或對其他變量的引用。

比較 JavaScript 中的數組

因為數組中的元素都有一個 和一個索引 (或職位),您需要決定如何 你想比較它們。以下是帶有代碼示例的選項。

檢查數組是否包含相同的值,無論順序如何

請注意,如果數組中有重複值,這將無法正常工作——只能比較每個數組中某個值的存在,而不是它出現的次數,因為不檢查每個元素的位置。

以下函數將檢查兩個數組是否包含相同的值,無論頻率或位置如何。

function compareArrayValues(array1, array2){
    
    # Get only the unique values in each array
    # This uses the new ES6 Set feature - a Set contains only unique values, so by converting an array to a Set and back, only the unique values are kept
    # the ellipsis (...) expands the values of the Set, which is faster to type than a foreach loop to add each value to the array
    array1 = [...new Set(array1)];
    array2 = [...new Set(array2)];

    # Sort the arrays so the values are in order and can be compared:
    array1.sort();
    array2.sort();

    # The arrays can now be compared directly.  A cheeky shortcut to do this is to convert them to a JSON string and compare those - if the strings match, the arrays are the same
    # This is again much faster than iterating through the array and comparing each value
    return JSON.stringify(array1) === JSON.stringify(array2);
}

如果數組包含相同的值,此函數將返回 TRUE,否則返回 FALSE。

檢查數組是否以相同的順序包含相同的值

以下函數直接比較數組——它們必須完全相同:

function compareArrays(array1, array2){
    
    # The arrays can be compared as-is as we want both the value and position of each element to be checked.  A cheeky shortcut to do this is to convert them to a JSON string and compare those - if the strings match, the arrays are the same
    # This is much faster than iterating through the array and comparing each value
    return JSON.stringify(array1) === JSON.stringify(array2);
}

如果數組完全相同,此函數將返回 TRUE,否則返回 FALSE。

在一個數組中查找不在另一個數組中的值

自 ECMA2015 版本以來的現代 JavaScript 版本(現在應該得到廣泛支持)提供了用於輕鬆過濾數組以發現它們之間的差異的函數。

下面的示例將採用 array1 中的元素 不在 array2 中的 並創建一個新的差異 和他們一起排列。

var differences = array1.filter(e => array2.indexOf(e) < 0);

這是如何工作的?

數組1 被過濾為僅包含未出現在 array2 中的值 .值是否出現在 array2 中 由是否有有效的索引(大於0的索引)決定。


Tutorial JavaScript 教程
  1. 使用無頭 CMS 庫快速跟踪您的 Angular 項目

  2. 我們製作了一個免費的 JS 庫,用於快速訪問有關人員和公司的專業數據

  3. 快速提示:使用 IndexedDB 在瀏覽器中存儲數據

  4. ES6 是否為對象屬性引入了明確定義的枚舉順序?

  5. 團隊成員名稱雜耍應用

  6. 如何等待功能完成?

  7. 使用 NFT 存儲在 IPFS 上存儲 NFT

  1. 顯示和隱藏密碼

  2. 同一頁面上有多個 Google Analytics(分析)gtag 跟踪 ID

  3. Vue Composition API 和 React Hooks 比較

  4. 用Javascript格式化電話號碼

  5. 在 JSON 將數據解析為 JS 對象之前檢查每個屬性。

  6. 使用 LSD 上的反應鉤子進行抽象

  7. 通過 Building Popsaga 掌握 React - 30 分鐘內的簡單 JavaScript 遊戲

  1. 看看 React 18 中的 `startTransition`

  2. 分步大 O 複雜性分析指南,使用 Javascript

  3. 理解設計模式:使用英雄示例的單例! (蝙蝠俠和蜘蛛俠在裡面)。

  4. 如何對齊 Material-UI 菜單項?