본문 바로가기
Front-End/Javascript

[Javascript] Type 체크

by kimik 2021. 6. 2.

1. Type of

 

Type of의 경우 피연산자의 데이터 타입을 문자열로 반환한다.

typeof '';              // string
typeof 1;               // number
typeof NaN;             // number
typeof true;            // boolean
typeof [];              // object
typeof {};              // object
typeof new String();    // object
typeof new Date();      // object
typeof /test/gi;        // object
typeof function () {};  // function
typeof undefined;       // undefined
typeof null;            // object
typeof undeclared;      // undefined

배열과 객체도 object로 표시하여, 일반 배열의 경우를 체크할 수 없고 DOM이나 기타 상황에서 type of로 체크하는 데에는 한계가 있다.

 

2. Object.prototype.toString

 

Object.prototype.toString 메소드는 객체를 나타내는 문자열을 반환한다.

 

var obj = new Object();
obj.toString(); // [object Object]

toString.call() 메소드를 사용하면 모든 타입의 타입 값을 알 수 있다.

 

Object.prototype.toString.call('');             // [object String]
Object.prototype.toString.call(new String());   // [object String]
Object.prototype.toString.call(1);              // [object Number]
Object.prototype.toString.call(new Number());   // [object Number]
Object.prototype.toString.call(NaN);            // [object Number]
Object.prototype.toString.call(Infinity);       // [object Number]
Object.prototype.toString.call(true);           // [object Boolean]
Object.prototype.toString.call(undefined);      // [object Undefined]
Object.prototype.toString.call();               // [object Undefined]
Object.prototype.toString.call(null);           // [object Null]
Object.prototype.toString.call([]);             // [object Array]
Object.prototype.toString.call({});             // [object Object]
Object.prototype.toString.call(new Date());     // [object Date]
Object.prototype.toString.call(Math);           // [object Math]
Object.prototype.toString.call(/test/i);        // [object RegExp]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(document);       // [object HTMLDocument]
Object.prototype.toString.call(argument);       // [object Arguments]
Object.prototype.toString.call(undeclared);     // ReferenceError

이를 이용하여 object 부분을 자르고 type부분만을 리턴하는 함수를 만들면,

function getType(target) {
  return Object.prototype.toString.call(target).slice(8, -1);
}

위와 같다.

 

 

 

3.instanceof

 

위의 Object.prototype.toString.call을 사용하면 객체의 종류까지 식별할 수 있지만, 객체의 상속관계까지는 체크 할 수 없다.

 

특히 DOM의 경우 toString.call을 사용하여 체크하면, 

 

HTMLDivElement, HTMLUListElement, HTMLLIElement, HTMLParagraphElement와 같은 다양한 형태로 출력되기 때문에 

 

HTMLElement인가를 체크하기위해서는 instanceof를 사용해야한다.

 

 instanceof 연산자는 피연산자인 객체가 우항에 명시한 타입의 인스턴스인지 여부를 알려주는 메소드

document.querySelector("body") instanceof HTMLElement  //true
"하나둘셋" instanceof HTMLElement //false

위처럼 HTMLElement를 체크 할 수 있습니다.

 

4. 유사배열 체크하기

 

유사배열 (대표적으로 NodeList, arguments 등)들은 Array.isArray로 type을 체크할시

Array.isArray(document.querySelectorAll("body")) //false

위와 같이 표시된다. 물론 유사배열을 배열로 체크하지 않아야할 경우도 있겠지만, 배열과 같이 순회할 수 있으며 call, apply를 

 

사용하여 배열의 메소드도 사용할 수 있다. 

 

유사배열역시 array로 체크하는 함수는 

const isArrayLike = function (collection) {
      // 배열 인덱스: 32bit 정수(2의 32제곱 - 1)
      // 유사 배열 인덱스: 자바스크립트로 표현할 수 있는 양의 정수(2의 53제곱 - 1)
      const MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
      // 빈문자열은 유사배열이다. undefined == null => true
      const length = collection == null ? undefined : collection.length;
      return typeof length === 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};

위와같다. 배열과 유사배열 모두 true를 반환한다.

댓글