패스트캠퍼스
javaScript-데이터 타입 확인
용용it
2023. 4. 17. 17:12
typeof를 사용하여 데이터의 타입을 확인할 수 있다.
console.log(typeof 'Hello' === 'string')
// true
console.log(typeof 123 === 'number')
// true
console.log(typeof false === 'boolean')
// true
console.log(typeof undefined === 'undefined')
// true
console.log(typeof null=== 'object')
// true
console.log(typeof [] === 'object')
// true
console.log(typeof {} === 'object')
// true
console.log(typeof function () {} === 'object')
// true
console.log([].constructor === Array )
// true
console.log ({}.constructor === Object )
// true
또한, checkType을 사용하여 데이터 타입의 확인도 가능하다.
function checkType(data) {
return Object.prototype.toString.call(data).slice(8, -1)
}
console.log(checkType(null))
// String
console.log(checkType(123))
// Number
console.log(checkType(false))
// Boolean
console.log(checkType(undefined))
// Undefined
console.log(checkType(null))
// Null
console.log(checkType([]))
// Array
console.log(checkType({}))
// Object
console.log(checkType(funcion () {}))
// Function