如何在 JavaScript 中使用“in”運算子?


在本文中,我們將探討 'in' 運算子以及如何在 JavaScript 中使用它。'in' 運算子是 JavaScript 中的內建運算子,用於檢查物件中是否存在特定屬性。如果屬性存在,則返回 true,否則返回 false。

語法

prop in object

引數

此函式接受以下引數:

  • prop − 此引數包含表示屬性名稱或陣列索引的字串或符號。

  • object − 將檢查此物件是否包含 prop。

返回值 − 此方法將返回 true 或 false,取決於物件中是否找到指定的屬性。

示例 1

在下面的示例中,我們將使用 JavaScript 中的 'in' 運算子來查詢屬性是否存在。

# index.html

<html>
<head>
   <title>IN operator</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      // Illustration of in operator
      const array = ['key', 'value', 'title', 'TutorialsPoint']
      
      // Output of the indexed number
      console.log(0 in array) //true
      console.log(2 in array) //true
      console.log(5 in array) //false
      
      // Output of the Value
      // you must specify the index number, not the value at that index
      console.log('key' in array) //false
      console.log('TutorialsPoint' in array) // false
      
      // output of the Array property
      console.log('length' in array)
   </script>
</body>
</html>

輸出

上述程式將在控制檯中產生以下輸出。

true
true
false
false
false
true

示例 2

在下面的示例中,我們演示了 in 運算子。

# index.html

<html>
<head>
   <title>IN operator</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      // Illustration of in operator
      const student = { name: 'Bill', class: 'IX', subjects: 'PCM', age: '16' };
      console.log('name' in student);
      delete student.name;
      console.log('name' in student);
      if ('name' in student === false) {
         student.name = 'Steve';
      }
      console.log(student.name);
   </script>
</body>
</html>

輸出

上述程式將在控制檯中產生以下結果。

true
false
Steve

更新於: 2022-04-28

146 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告