Object.prototype.toString.call ( target )
해당 오브젝트의 타입을 알려줍니다.
const a = 123;
const b = "test";
const c = [1, 2, 3];
const d = () => { alert("is function!"); }
const aType = Object.prototype.toString.call(a); //[object Number]
const bType = Object.prototype.toString.call(b); //[object String]
const cType = Object.prototype.toString.call(c); //[object Array]
const dType = Object.prototype.toString.call(d); //[object Function]
//응용버전 - 타입 판별 방법.
const isFunction = /Function/.test(dType); //1. 정규식으로 판별
const isFunction2 = dType.indexOf("Function"); //2. indexOf 로 contain 판별
alert(
"aType : " + aType + "\n" +
"bType : " + bType + "\n" +
"cType : " + cType + "\n" +
"dType : " + dType + "\n" +
"isFunction : " + isFunction + "\n" +
"isFunction2 : " + isFunction2
);
/* 결과
aType : [object Number]
bType : [object String]
cType : [object Array]
dType : [object Function]
isFunction : true
isFunction2 : 8
*/
'Javascript > 문법' 카테고리의 다른 글
[JS] 유용한 정규식 (콤마, 전화번호 등) ( + ascii 문자) (0) | 2023.10.30 |
---|---|
[JS] (`${함수명}`) 함수 내용을 문자열로 출력하기 (0) | 2023.10.09 |
[JS] &&, ||, ?, ?? 연산자 결과 확인 (0) | 2023.10.09 |