Object Type 알아내기
typeof
보통 javascript에서 데이터 타입을 알아내기 위해서 typeof 연산자 를 사용합니다. typeof를 통해 javascript의 다음과 같은 데이터 타입을 알아낼 수 있습니다.
x typeof undefined // "undefined"
typeof 1 // "number"
typeof {} // "object"
typeof true // "boolean"
typeof "str" // "string"
function func() {}
typeof func // "function"
typeof Symbol("sym"); // "symbol"
그렇다면 이 이외에 Array 나, Null, Date 와 같이 Object의 타입은 어떨까요.
xxxxxxxxxx
typeof [] // "object"
typeof null // "object"
const date = new Date();
typeof date // "object"
예상하던 바와 달리 Array, Null, Date 모두 "object"라는 결과를 보여 줍니다.
그럼 typeof 를 사용하는 방법 이외에 Object 인지 Array 인지, Null 인지 어떻게 구분할 수 있을 까요. 바로 다음과 같이 Object.prototypr.toString을 이용하면 됩니다.
Object.prototype.toString
xxxxxxxxxx
function getType(data) {
return Object.prototype.toString.call(data);
}
xxxxxxxxxx
function getType(data) {
return Object.prototype.toString.call(data);
}
getType({}); // "[object Object]"
getType(6); // "[object Number]"
getType(true); // "[object Boolean]"
getType("string"); // "[object String]"
getType([1, 2]); // "[object Array]"
getType(undefined); // "[object undefined]"
getType(null) // "[object Null]"
function func(){}
getType(func); // "[object function]"
getType(new Date()) // "[object Date]"
'Javascript' 카테고리의 다른 글
!! 연산자 (0) | 2019.03.05 |
---|