Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript 객체에 키가 있는지 확인하는 방법은 무엇입니까?

<시간/>

키가 자바스크립트 객체에 존재하는지 여부를 확인하는 몇 가지 방법이 있습니다.

아래와 같이 '직원' 개체가 있다고 가정해 보겠습니다.

   var employee = {
      name: "Ranjan",
      age: 25
   }

이제 employee 객체에 'name' 속성이 존재하는지 확인해야 합니다.

1) '인' 연산자

객체에 'in' 연산자를 사용하여 속성을 확인할 수 있습니다. 'in' 연산자는 개체의 실제 속성을 찾지 못하면 상속된 속성도 찾습니다.

다음 예에서 'toString'이 있는지 여부가 확인되면 'in' 연산자는 객체의 속성을 자세히 조사합니다. 부재가 확인되면 객체의 기본 속성이 나타납니다. 'toString'은 기본 속성이므로 출력에 표시된 대로 'true'를 표시합니다.

<html>
<body>
<script>
   var employee = {
      name: "Ranjan",
      age: 25
   }
   document.write("name" in employee);
   document.write("</br>");
   document.write("salary" in employee);
   document.write("</br>");
   document.write("toString" in employee);
</script>
</body>
</html>

출력

true
false
true


2) hasOwnProperty()

이 방법은 실제 속성에 대해서만 개체를 ​​조사하지만 어떤 종류의 상속된 속성도 조사하지 않습니다. 실제 속성이 있는 경우 이 메서드는 가용성에 따라 true 또는 false를 표시합니다.

다음 예에서는 'toString'과 같은 상속된 속성도 검색하여 출력에 표시된 대로 false를 표시합니다.

<html>
<body>
<script>
   var employee = {
      name: "Ranjan",
      age: 25
   }
   document.write(employee.hasOwnProperty('toString'));
   document.write("</br>");
   document.write(employee.hasOwnProperty('name'));
   document.write("</br>");
   document.write(employee.hasOwnProperty('salary'));
</script>
</body>
</html>

출력

false
true
false