Home  >  Article  >  Web Front-end  >  How to use "in" operator in JavaScript?

How to use "in" operator in JavaScript?

WBOY
WBOYforward
2023-09-12 17:13:09807browse

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

In this article, we will explore the “in” operator and how to use it in JavaScript. The in operator is a built-in operator in JavaScript that is used to check whether a specific property exists in an object. Returns true if the property exists, false otherwise.

Syntax

prop in object

Parameters

This function accepts the following parameters as mentioned below-

  • prop - This parameter holds a string or symbol representing the property name or array index.

  • object - will check if the object contains prop .

Return value - if The specified property is found in the object, this method returns true or false.

Example 1

In the following example, we will use the 'inin' operator in JavaScript to find whether a property exists.

# 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>

Output

The above program will produce the following output in the console.

true
true
false
false
false
true

Example 2

In the following example, we demonstrate the in operator.

# 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>

Output

The above program will produce the following results in the console.

true
false
Steve

The above is the detailed content of How to use "in" operator in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete