본문 바로가기

Language/JS

Type 확인

//데이터 타입 확인
// console.log(typeof a)
// 근데 이걸로는 null, 배열[] 객체{} 는 확인하지 못한다.
// Js에서는 함수도 타입으로 친다. 


console.log(typeof 'hello' === 'string')
console.log(typeof 123 === 'number')
console.log(typeof false === 'boolean')
console.log(typeof undefined === 'undefined')
console.log(typeof null ==='object')
console.log(typeof[] === 'object')
console.log(typeof{} === 'object')
console.log(typeof function () {} ==='function')




// [] 배열은 Array라는 함수에서 확장되어 만들어진 것이다. 
// [].constructor 는 배열의 최고조상이 무엇인지 알려준다. -> 조상은 Array(){}라는 함수였다. 
// 따라서 [].constructor는 Array 임으로 밑의 값은 참이다.
// 함수 자체를 비교할 때는 "" 같은 애들 필요 없다. 
console.log([].constructor ==Array)


// 객체도 마찬가지로 .constructor를 쓰면 Object라는 함수임을 알 수 있다.
console.log({}.constructor == Object)

// console.log(null.constructor) null은 함수가 아니기에 해당 스킬로 무슨 타입인지 알아내지 못함.
// console.log(Object.prototype.toString.call(null).slice(8, -1) === 'Null')

  console.log(checkType('Hello'))
  console.log(checkType(123))
  console.log(checkType(false))
  console.log(checkType([]))
  console.log(checkType({}))
  console.log(checkType(function () {}))

function checkType (data) {
  return Object.prototype.toString.call(data).slice(8,-1)
}