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
*/

 

+ Recent posts