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
'패스트캠퍼스' 카테고리의 다른 글
javaScript-부정, 비교 연산자 (2) | 2023.04.17 |
---|---|
javaScript-산술, 할당, 증감 연산자 (0) | 2023.04.17 |
javaScript-참과 거짓(Truthy & Falsy) (0) | 2023.04.17 |
javaScript-형 변환(Type Conversion) (0) | 2023.04.17 |
javaScript-객체(Object) (0) | 2023.04.14 |