JavaScriptで「in」演算子を使用するにはどうすればよいですか?

WBOY
リリース: 2023-09-12 17:13:09
転載
804 人が閲覧しました

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

この記事では、「in」演算子とそれを JavaScript で使用する方法について説明します。 in 演算子は、オブジェクトに特定のプロパティが存在するかどうかを確認するために使用される JavaScript の組み込み演算子です。プロパティが存在する場合は true、存在しない場合は false を返します。

構文

prop in object
ログイン後にコピー

パラメータ

この関数は、後述するように次のパラメータを受け入れます。

  • prop - このパラメータは、プロパティ名または配列インデックスを表す文字列または記号を保持します。

  • object - オブジェクトに prop が含まれているかどうかを確認します。

戻り値 - if指定されたプロパティがオブジェクト内で見つかった場合、このメソッドは 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

<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>
ログイン後にコピー

出力

上記のプログラムは、コンソールに次の結果を生成します。

えええええ

以上がJavaScriptで「in」演算子を使用するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!