728x90
// [ JS 데이터 ] 데이터 타입 확인
const a = 123
console.log(typeof a) // number
console.log(typeof 'Hello') // string
console.log(typeof 'Hello' === 'string') // true
console.log(typeof 123 === 'number') // true
console.log(typeof false === 'boolean') // true
console.log(typeof undefined === 'undefined') // true
// null / [] (배열) / {} (객체)
// 는 모두 object 라는 단어로 확인이 된다.
// 즉, null 과 배열, 객체는 typeof로 구분이 불가능 하다. (모두 object 로 나오니까)
console.log(typeof null) // object
console.log(typeof null === 'object') // true
console.log(typeof [] === 'object') // true
console.log(typeof {} === 'object') // true
// 익명 함수는 함수라는 하나의 데이터 이기 때문에, 문자 데이터 'function' 으로 비교가 가능 하다.
console.log(typeof function () {
} === 'function') // true
// 기본적으로 대괄호 [] 를 사용하는 모든 배열 데이터에
// constructor 속성을 사용 하면,
// 그 배열 데이터에 해당하는 Array 전역 함수가 표시가 된다.
// Array 라는 함수는 이미 자바스크립트에 들어 있는 전역 함수 이다.
// 배열 데이터는 Array 라는 이름의 전역 함수에서 확장 되서 만들어진 데이터 이다.
console.log([].constructor) // f Array() { [native code] }
// 따라서 배열 데이터는 일치 연산자를 통해 Array 함수 그 자체와 비교가 가능 하다.
// 예시)
console.log([].constructor === Array) // true
// 마찬가지로 객체 데이터도 constructor 속성을 사용 하면,
// 객체 데이터에 해당 하는 Object 라는 전역 함수가 표시가 된다.
console.log({}.constructor) // f Object() { [native code] }
console.log({}.constructor === Object) // true
// 하지만, null은 constructor 속성이 존재 하지 않는다.
// console.log(null.constructor)
// 로그를 찍어보면, 아래의 에러가 발생 한다.
// main.js:53 Uncaught TypeError: Cannot read properties of null (reading 'constructor')
// 그러면 null 은 어떻게 확인 할 수 있을까 ?
// 아래와 같이 작성 하여 확인이 가능 하다 !
console.log(Object.prototype.toString.call(null)) // [object Null]
// 콘솔 로그를 사용 해서 [object Null] 라는 문자를 얻게 되었다.
// 여기서 실질적으로 필요한 것은 Null 이기 때문에, 메서드를 사용 해서 원하는 단어를 구해보자.
console.log(Object.prototype.toString.call(null).slice(8, -1)) // Null
// slice() 메서드를 사용해서, 8번째 단어 부터 마지막의 바로 앞 단어 까지만 구할 수 있다.
console.log(Object.prototype.toString.call(null).slice(8, -1) === 'Null') // true
// 그러면 결국 Null 데이터도 확인 할 수 있게 됬다.
// =================================================================================
// 정리하자면,
// 제일 간단한 방식인 typeof 키워드를 사용 해서 데이터 타입을 확인 할 수 있다.
// 하지만, 이 방법으로는 배열, 객체, null 데이터 구분은 할 수 없다.
// 그래서 .constructor 속성을 사용 해서 데이터 타입을 확인 할 수 있었다.
// 하지만, 이것도 배열과 객체는 확인이 가능 하지만, null 데이터는 구분 할 수 없었기에,
// 다소 복잡하지만, Object.prototype.toString.call(데이터) 을 작성 해서 해결 할 수 있었다.
// 이 마지막 방법은 null 데이터 뿐만 아니라, 모든 데이터를 확인 할 수 있는 방법 인데,
// 재사용이 가능하도록 함수를 아래에서 작성해보자.
function checkType(data) { // 재사용 할 수 있는 함수를 작성.
return Object.prototype.toString.call(data).slice(8, -1)
}
console.log(checkType([])) // Array
console.log(checkType({})) // Object
console.log(checkType(null)) // Null
console.log(checkType('Hello')) // String
console.log(checkType(123)) // Number
console.log(checkType(false)) // Boolean
console.log(checkType(undefined)) // Undefined
console.log(checkType(function () { // Function
}))
// 모든 데이터를 확인 할 수 있는 것을 확인 할 수 있다.
반응형
'자바스크립트 (JavaScript) > 이론' 카테고리의 다른 글
[ 연산자와 구문 ] 부정, 비교 연산자 (0) | 2023.11.01 |
---|---|
[ 연산자와 구문 ] 산술, 할당, 증감 연산자 (0) | 2023.10.31 |
[ JS 데이터 ] 참과 거짓 (Truthy & Falsy) (1) | 2023.10.31 |
[ JS 데이터 ] 형 변환 (Type Conversion) (1) | 2023.10.31 |
[ JS 데이터 ] 참조형 - Function (0) | 2023.10.30 |