JavaScript에서 'in' 연산자를 어떻게 사용하나요?

WBOY
풀어 주다: 2023-09-12 17:13:09
앞으로
804명이 탐색했습니다.

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

이 글에서는 “in” 연산자와 이를 JavaScript에서 사용하는 방법을 살펴보겠습니다. in 연산자는 객체에 특정 속성이 존재하는지 확인하는 데 사용되는 JavaScript의 내장 연산자입니다. 속성이 존재하면 true를 반환하고 그렇지 않으면 false를 반환합니다.

Syntax

prop in object
로그인 후 복사

Parameters

이 함수는 아래 언급된 매개변수를 허용합니다. -

  • prop - 이 매개변수는 속성 이름이나 배열 인덱스를 나타내는 문자열이나 기호를 보유합니다.

  • object - 객체에 prop이 포함되어 있는지 확인합니다.

Return Value - 이 메소드는 지정된 속성이 객체에 있으면 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>
로그인 후 복사

Output

위 프로그램은 콘솔에 다음과 같은 출력을 생성합니다.

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>
로그인 후 복사

Output

위 프로그램은 콘솔에 다음과 같은 결과를 생성합니다.

rreee

위 내용은 JavaScript에서 'in' 연산자를 어떻게 사용하나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!