Study/JavaScript

[JS] in & hasOwnProperty

taecongs 2023. 8. 30. 19:06

알고있으면 좋은 Javascript Tip✨


in 연산자

  • in연산자는 특정 속성이 해당 객체에 있는지 여부를 boolean으로 리턴해준다.

(1) array의 경우

  • array에서 in연산자를 사용하면, 인덱스에 대해서만 체크할 수 있다.
const arr = ['dog', 'cat', 'rabbit'];

console.log(0 in arr);       // true
console.log((1+1) in arr);   // true
console.log('dog' in arr); // false

(2) string의 경우

  • string에서는 in연산자를 사용하면 에러가 발생한다.
  • 하지만, new String로 선언하면 string에서 사용할 수 있는 속성(length)에 대해서 체크할 수 있다.
const text = new String('hello');
console.log('length' in text);  // true

// console.log('length' in text) 결과는?
0 : "h"
1 : "e"
2 : "l"
3 : "l"
4 : "o"
length : 5

(3) object의 경우

  • object에서 in연산자를 사용하면, 해당 객체에 특정 속성이 있는지 체크할 수 있다.
const obj = {'a': 1, 'b': 2, 'c': 3};
console.log('a' in obj);  // true
console.log(1 in obj);    // false

(4) 상속된 속성

  • JS에서는 객체를 생성하면 우리는 JS에서 제공하는 내장 메서드에 접근할 수 있다.
  • 이는 JS의 프로토타입 체인 때문인데, 특이한 점은 이 체인으로 인해 객체의 내장 속성을 체크할 수 있다.
console.log('slice' in []); // true

 

hasOwnProperty

  • hasOwnProperty()은 해당 객체에 특정 속성이 있는지 여부를 boolean으로 리턴해준다.

(1) array의 경우

const arr = ['dog', 'cat', 'rabbit'];

console.log(arr.hasOwnProperty(1));       // true
console.log(arr.hasOwnProperty('dog')); // false

(2) string의 경우

  • new 생성자를 이용해 String을 선언하면, length 속성이 있는지 체크할 수 있다.
const text = new String('hello');
console.log(text.hasOwnProperty('length'));  // true

(3) object의 경우

const obj = {'a': 1, 'b': 2, 'c': 3};

console.log(obj.hasOwnProperty('a'));  // true
console.log(obj.hasOwnProperty(1));    // false

(4) 상속된 속성

  • hasOwnProperty()는 프로토타입 체인으로 인해 객체에서 기본 제공되는 속성에는 접근할 수 없다.
console.log([].hasOwnProperty('slice')); // false

'Study > JavaScript' 카테고리의 다른 글

[JS] flat & flatMap  (0) 2023.08.30
[JS] export & import  (0) 2023.08.30
[JS] min & max  (0) 2023.08.09
[JS] URLSearchParams  (0) 2023.08.01
[JS] closest & parentElement  (0) 2023.07.26