搜尋
首頁web前端js教程如何使用jQuery/JavaScript比較兩個JavaScript陣列物件?

如何使用jQuery/JavaScript比較兩個JavaScript陣列物件?

在JavaScript中,陣列是一個帶有索引作為鍵和陣列值作為陣列物件特定鍵的值的物件。有時,我們需要檢查兩個陣列是否相同。

我腦中首先想到的解決方案是使用等號運算符,像array1 == array2這樣比較。哎呀!這樣是行不通的,因為數組是一個對象,在JavaScript中我們不能直接比較兩個對象。所以,我們必須比較數組的每個元素。

在本教學中,我們將學習使用不同的方法來比較兩個JavaScript陣列物件。

Use the sort() method of JavaScript and compare every element

sort()方法允許我們在JavaScript中對陣列值進行排序。之後,我們可以使用for迴圈來比較數組中每個索引處的元素。如果任何索引處的元素不匹配,我們可以說這兩個數組物件是不同的。

Syntax

使用者可以依照下列語法使用sort()方法和for迴圈來比較兩個陣列物件。

// sort arrays first
arra1.sort();
array2.sort();
   if (array1.length != array2.length) {
      // arrays are not the same
   } else {
      for () {
         // if elements at index i are not the same, return false
      }
   }
}
// both arrays are the same

Algorithm

使用者可以按照以下演算法進行操作。

  • Step 1 − Use the sort() method to sort both arrays.

  • 步驟2 - 比較兩個陣列的長度;如果長度不相同,則傳回false,表示兩個陣列不相同。

  • 步驟 3 − 如果兩個陣列的長度相同,則使用for迴圈遍歷兩個陣列。

  • Step 4 − Compare the elements of both arrays at every index, and if the elements at the index don’t match, return false.

  • #步驟 5 - 如果兩個陣列中的所有元素都匹配,則兩個陣列相同。

Example

在下面的範例中,我們建立了兩個數字數組,並使用sort()方法對它們進行排序。然後,我們使用for迴圈來比較兩個陣列的每個元素。

In the output, users can see that both arrays are the same as both arrays contain the same values.

<html>
<body>
   <h3>Using the <i>array.sort()</i> method and <i>for</i> loop to check if two arrays are the same using JavaScript </h2>
   <button onclick = "checkArray()"> Compare arrays </button>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let array1 = [32, 32, 54, 1, 2, 3, 4];
      let array2 = [1, 2, 3, 4, 32, 54, 32];
      output.innerHTML += "The first array values are " + array1 + "<br>";
      output.innerHTML += "The second array values are " + array2 + "<br>";
      function checkArray() {
         array1.sort();
         array2.sort();
         if (array1.length != array2.length) {
            output.innerHTML += "Both arrays are not same!";
            return false;
         } else {
            for (let i = 0; i < array1.length; i++) {
               if (array1[i] != array2[i]) {
                  output.innerHTML += "Both arrays are not same!";
                  return false;
               }
            }
         }
         output.innerHTML += "Both arrays are the same!";
         return true;
      }
   </script>
</body>
</html>

使用forEach迴圈和indexOf()方法

We can use the forEach loop to iterate through every array element. The indexOf() method finds the first occurrence of the element in the array and returns -1 if the reference array doesn’t contain the element.

#Syntax

使用者可以依照下列語法使用forEach迴圈和indexOf()方法來比較兩個陣列物件。

if (array2.length != array1.length) {
   // array are not the same
   return false;
} else {
   array1.forEach((element) => {
      if (array2.indexOf(element) == -1) {
         return false;
      }
   })
}

Algorithm

In this algorithm, we don’t need to sort the arrays like the first approach.

  • 步驟 1 - 檢查兩個陣列的長度是否相同;如果不相同,則傳回 false。

  • Step 2 − If the lengths are the same, use the forEach() loop to iterate through every element.

  • #步驟 3 − 對於陣列1的每個元素,使用indexOf()方法檢查其是否存在於陣列2中。

  • 第四步驟 - 如果indexOf()方法對於任何一個元素傳回-1,則表示兩個陣列不相同。

Example

In the example below, when the user clicks the button, it will invoke a compareArray() function. The compareArray() function compares the two arrays of string elements.

在輸出中,使用者可以觀察到兩個陣列不相同,因為兩個陣列的值是不同的。

<html>
<body>
   <h3 id="Using-the-i-forEach-loop-and-indexOf-method-i-to-check-if-two-arrays-are-the-same-using-JavaScript">Using the <i>forEach() loop and indexOf() method</i> to check if two arrays are the same using JavaScript </h3>
   <button onclick = "compareArray()"> Compare arrays</button>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let array1 = ["Hello", "Hi", "How"];
      let array2 = ["Are", "You", "!"];
      output.innerHTML += "The first array values are " + array1 + " <br>";
      output.innerHTML += "The second array values are " + array2 + " <br>";
      function compareArray() {
         var isSame = true;
         if (array2.length != array1.length) {
            output.innerHTML += "Both arrays are not same!";
            return false;
         } else {
            array2.forEach((element) => {
               if (array1.indexOf(element) == -1) {
                  isSame = false;
               }
            })
         }
         if (isSame) {
            output.innerHTML += "Both arrays are the same!";
         } else {
            output.innerHTML += "Both arrays are not same!";
         }
         return true;
      }
   </script>
</body>
</html>

我們已經學習了兩種不同的方法來比較JavaScript中的兩個陣列。使用者可以使用第一種方法來比較包含重複值的數組,而第二種方法只適用於比較包含唯一值的數組。

Also, users can use the JSON.stringify() method to compare the array of objects and sorted arrays.

以上是如何使用jQuery/JavaScript比較兩個JavaScript陣列物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
Python vs. JavaScript:開發環境和工具Python vs. JavaScript:開發環境和工具Apr 26, 2025 am 12:09 AM

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

JavaScript是用C編寫的嗎?檢查證據JavaScript是用C編寫的嗎?檢查證據Apr 25, 2025 am 12:15 AM

是的,JavaScript的引擎核心是用C語言編寫的。 1)C語言提供了高效性能和底層控制,適合JavaScript引擎的開發。 2)以V8引擎為例,其核心用C 編寫,結合了C的效率和麵向對象特性。 3)JavaScript引擎的工作原理包括解析、編譯和執行,C語言在這些過程中發揮關鍵作用。

JavaScript的角色:使網絡交互和動態JavaScript的角色:使網絡交互和動態Apr 24, 2025 am 12:12 AM

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

C和JavaScript:連接解釋C和JavaScript:連接解釋Apr 23, 2025 am 12:07 AM

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

從網站到應用程序:JavaScript的不同應用從網站到應用程序:JavaScript的不同應用Apr 22, 2025 am 12:02 AM

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python vs. JavaScript:比較用例和應用程序Python vs. JavaScript:比較用例和應用程序Apr 21, 2025 am 12:01 AM

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C/C在JavaScript口譯員和編譯器中的作用C/C在JavaScript口譯員和編譯器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在行動中:現實世界中的示例和項目JavaScript在行動中:現實世界中的示例和項目Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具