首頁  >  文章  >  web前端  >  如何在 JavaScript 中使用「in」運算子?

如何在 JavaScript 中使用「in」運算子?

WBOY
WBOY轉載
2023-09-12 17:13:09810瀏覽

如何在 JavaScript 中使用“in”运算符?

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

語法

prop in object

參數

此函數接受如下所述的以下參數-

  • prop - 此參數保存表示屬性名稱或陣列索引的字串或符號。

  • object - 將檢查該物件是否包含prop .

傳回值 - 如果在物件中找到指定的屬性,此方法將傳回true 或false。

範例 1

在下面的範例中,我們將使用 JavaScript 中的 'inin' 運算子來尋找屬性是否存在。

# 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 = [&#39;key&#39;, &#39;value&#39;, &#39;title&#39;, &#39;TutorialsPoint&#39;]
      
      // 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(&#39;key&#39; in array) //false
      console.log(&#39;TutorialsPoint&#39; in array) // false
      
      // output of the Array property
      console.log(&#39;length&#39; in array)
   </script>
</body>
</html>

輸出

#上述程式將在控制台中產生下列輸出。

true
true
false
false
false
true

範例 2

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

# index.html p>

<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: &#39;Bill&#39;, class: &#39;IX&#39;, subjects: &#39;PCM&#39;, age: &#39;16&#39; };
      console.log(&#39;name&#39; in student);
      delete student.name;
      console.log(&#39;name&#39; in student);
      if (&#39;name&#39; in student === false) {
         student.name = &#39;Steve&#39;;
      }
      console.log(student.name);
   </script>
</body>
</html>

輸出

#上述程式將在控制台中產生下列結果。

true
false
Steve

以上是如何在 JavaScript 中使用「in」運算子?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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