JavaScript/JavaScript 문법

[JavaScript]객체에 프로퍼티가 존재하는지 체크하는 방법

DevStory 2021. 8. 19.

JavaScriptin 연산자는 프로퍼티가 객체에 존재하는지 체크하는 연산자입니다.

 

사용 방법은 심플합니다.

 

좌변의 피연산자는 존재유뮤를 체크할 프로퍼티 이름을 문자열(혹은 문자열로 변환이 가능한 값)로 받습니다.

 

우변의 피연산자는 객체 또는 배열이 올 수 있습니다.

프로퍼티명 in 객체명

프로퍼티가 객체에 존재하면 true를 반환하며, 존재하지 않을 경우 false를 반환합니다.

 

객체가 존재하지 않는 경우에는 에러가 발생합니다.

 

이번 포스팅에서는 in 연산자 사용 방법을 정리합니다.

 


배열의 프로퍼티를 체크

var arr = ['A', 'B', 'C'];

// 0을 문자열로 형변환 후 체크합니다.
console.log(0 in arr);
// true

console.log('0' in arr);
// true

console.log('length' in arr);
// true

// length는 문자열로 형변환 불가능합니다.
console.log(length in arr);
// false

console.log('A' in arr);
// false

console.log(3 in arr);
// false

Chrome Console에서 배열 arr의 값을 출력해보면, 다음 사진과 같습니다.

'A' in arr에서 false가 출력된 이유는 'A'는 배열의 프로퍼티가 아니라 값입니다.

 

배열은 index가 프로퍼티입니다.

 

3 in arr에서 false가 출력된 이유는 존재하지 않는 index이므로 false가 출력됩니다.

 

즉, 배열은 값이 아니라 index로 체크해야 합니다.


객체의 프로퍼티를 체크

window 객체의 프로퍼티를 체크하는 코드입니다.

console.log(LUX in window);
// false

console.log('LUX' in window);
// true

// 'TEST' 프로퍼티는 존재하지 않습니다.
console.log('TEST' in window);
// false

// window의 하위 프로퍼티의 프로퍼티를 체크할 수 있습니다.
console.log('addData' in window.LUX)
// true

Chrome Console에서 window 객체를 출력해보면, 다음 사진과 같습니다.

window 객체에 'LUX' 프로퍼티가 존재하므로 'LUX' in windowtrue를 반환합니다.

 

in 연산자를 사용하여 객체의 프로퍼티의 프로퍼티도 체크할 수 있습니다.

 

window 객체의 'LUX' 프로퍼티를 점 표기법을 사용하여 window.LUX로 접근합니다.

 

window.LUXaddData 프로퍼티가 존재하는지 체크하였습니다.


사용자가 정의한 객체의 프로퍼티를 체크

사용 방법은 객체의 프로퍼티를 체크하는 방법과 동일합니다.

var student = {
  Name : "JaeSeong", 
  Contact: {
    email: "wotjd2386@gmail.com",
    phone: "010-1234-5678"
  }
};

console.log('Name' in student);
// true

console.log('email' in student.Contact);
// true

Html 요소에 프로퍼티가 존재하는지 체크

Check If You Are On a Touch Enabled Devices에 작성된 코드입니다.

 

터치 가능한 장치인 경우 true를 반환하며, 터치가 불가능한 장치인 경우 false를 반환합니다.

function isTouchSupported() {
  var msTouchEnabled = window.navigator.msMaxTouchPoints;
  var generalTouchEnabled = "ontouchstart" in document.createElement("div");

  if (msTouchEnabled || generalTouchEnabled) {
    return true;
  }
  return false;
}

 

반응형

댓글