首頁  >  文章  >  web前端  >  如何使用 JavaScript 檢查物件是否為空?

如何使用 JavaScript 檢查物件是否為空?

王林
王林轉載
2023-09-14 14:17:021398瀏覽

如何使用 JavaScript 检查对象是否为空?

在 JavaScript 中,物件是最重要的資料類型,我們在使用 JavaScript 框架開發應用程式時大部分時間都需要它。有時,我們需要檢查一個物件是否為空,並根據物件值執行操作。

例如,您正在從資料庫中取得資料;如果沒有找到,您可以獲得一個空物件。當您對空物件執行某些操作或執行某些方法時,它會在程式中引發錯誤。因此,最好先檢查物件是否為空。

我們將學習三種使用 JavaScript 檢查物件是否為空的方法。

使用Object.keys()方法

我們可以使用Object.keys()方法來取得單一陣列中物件的鍵。之後,我們可以使用陣列的 length 屬性來檢查陣列的長度。如果鍵數組的長度為0,則表示該物件不包含任何鍵,且該物件為​​空。

文法

使用者可以依照下面的語法使用Object.keys()方法檢查物件是否為空。

let obj1Len = Object.keys(obj1).length;
if (obj1Len == 0) {
   
   // object is empty
} else {
   
   // object is not empty
} 

在上面的語法中,Object.keys()傳回obj1的所有鍵的數組,我們使用length屬性來取得它的長度。使用上面的語法,我們可以使用 Object.keys() 方法來取得所有鍵的數組,並且我們也可以使用 length 屬性來檢查數組的長度

範例

在下面的範例中,我們建立了兩個不同的物件。 obj1 包含一些屬性,而 obj2 為空且不包含任何單一屬性。

之後,我們對兩個物件使用 Object.keys() 方法來取得鍵數組並檢查數組的長度以確保物件為空或至少包含一個屬性。

<html>
<body>
   <h3>Using the<i> object.keys() </i>method to check whether the object contains some value or not</h3>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      let obj1 = {
         prop1: 10,
         prop2: "Hi",
      };
      let obj2 = {};
      
      // get the array of all keys using the Object.keys() method,
      
      // check the length of the array using the length property
      let obj1Len = Object.keys(obj1).length;
      if (obj1Len != 0) {
         output.innerHTML += "The value of obj1 is " + JSON.stringify(obj1) + "</br>";
      } else {
         output.innerHTML += "The obj1 object is empty! </br>";
      }
      let obj2Len = Object.keys(obj2).length;
      if (obj2Len != 0) {
         output.innerHTML += "The value of obj1 is " + obj2 + "</br>";
      } else {
         output.innerHTML += "The obj2 object is empty! </br>"; 
      }
   </script>
</body>
</html>

使用 for-in 迴圈

for-in 迴圈允許我們迭代物件的鍵。我們可以使用 for-in 循環遍歷物件的每個鍵。在這裡,我們將使用 for-in 循環並檢查如果它對物件進行了一次迭代,則該物件至少包含一個屬性並且不為空。

文法

使用者可以依照下列語法使用 for-in循環檢查物件是否為空。

function isObjectEmpty(object) {
   for (ele in object) {
      
      // object is not empty
      return;
   }
   
   // if control comes here, the object is empty
} 

在上面的語法中,如果發生了 for 迴圈的單次迭代,則表示我們已經確保該物件至少包含一個屬性。因此,我們在 for-in 迴圈的第一次迭代之後使用 return 關鍵字終止函數。

範例

在下面的範例中,我們建立了兩個不同的物件。此外,我們還建立了 isObjectEmpty() 函數,該函數會根據物件是否為空列印不同的訊息。

我們使用不同的物件呼叫了isObjectEmpty()函數兩次,使用者可以觀察其輸出。

<html>
<body>
   <h3>Using the <i>for-in loop</i> to check whether the object contains some value.</h3>
   <p id="output"></p>
   <script>
      let output = document.getElementById("output");
      
      // creating the objects
      let obj1 = {
         prop1: false,
      };
      let obj2 = {};
      
      // creating a function to check object is empty or not
      function isObjectEmpty(object) {
         for (ele in object) {
            
            // if any single iteration occurs using a for-in loop, it means the object contains at least one property
            output.innerHTML += "The object " + JSON.stringify(object) + " is not empty! </br>";
            return;
         }
         output.innerHTML += "The object " + JSON.stringify(object) + " is empty! </br>";
      }
      
      // calling the isObjectEmpty() function by passing different objects as an argument
      isObjectEmpty(obj1);
      isObjectEmpty(obj2);
   </script> 
</body>
</html>

使用 JSON.stringify() 方法

JSON.stringify() 方法將任何值轉換為我們作為該方法的參數傳遞的字串。空物件的語法類似於 {},stringify() 方法總是傳回空物件的「{}」。

因此,我們可以將 stringify() 方法的回傳值與「{}」進行比較,確定該物件是否為空。

文法

使用者可以依照以下語法使用 JSON.stringify() 方法檢查物件是否為空。

if(JSON.stringify(education) == "{}") {
   
   // object is empty
} else {
   
   // object is not empty
}

在上述語法中,如果 education 物件為空,JSON.stringify() 方法將傳回「{}」。

範例

在下面的範例中,我們建立了 education 對象,其中包含一些屬性。因此,JSON.stringify()方法不會傳回“{}”,但會傳回 education 物件的字串值。因此,使用者可以觀察到顯示教育對像不為空的輸出。

<html>
<body> 
   <h3> Using the<i> JSON.stringify() method </i> to check whether object contains some value or not.</h3>
   <p id="output"></p>
   <script>
      let output = document.getElementById("output");
      
      // creating the objects
      let education = {
         totalYears: 12,
         school: "Online",
      };
      
      // convert object to string,
      
      // if object is empty, the JSON.stringify() method will return "{}"
      if (JSON.stringify(education) == "{}") {
         output.innerHTML += "Object is empty!";
      } else {
         output.innerHTML += "Education object is not empty!";
      }
   </script>
</body>
</html>

我們學習了三種檢查物件是否為空的方法。第一種和第三種方法只有一行程式碼;使用者需要寫 3 到 4 行才能使用第二行。因此,最好使用第一種和第三種方法中的任何一種,以獲得更好的程式碼可讀性。

以上是如何使用 JavaScript 檢查物件是否為空?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除