핀테크 서비스 프론트엔드 개발자 취업 완성 2기/JS
[JS] 데이터 타입 확인 함수
flyda
2022. 4. 14. 14:33
실습 내용
프로젝트에서 데이터 타입을 확인하는 함수를 js파일로 작성한 뒤 import로 가져와서 사용하는 방법을 실습한다.
코드는 다음과 같다.
html 파일
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./main.js"></script>
<script src="./test.js"></script>
</head>
<body>
<h1>hello!!</h1>
</body>
</html>
main.js 파일
console.log(typeof "hello dada")
console.log(typeof 123)
console.log(typeof true)
console.log(typeof undefined)
console.log(typeof null)
console.log(typeof {})
console.log(typeof [])
크롬의 개발자 도구 콘솔 창을 살표보면, 먼저 main.js 파일에서 typeof를 통해서 각 데이터의 타입을 확인할 수 있다. 하지만. typeof의 경우 null, object, array(배열)는 모두 object로 표시된다.

수정
그래서 getType.js라는 파일을 생성해서 다음과 같이 코드를 작성해주고 함수가 필요한 파일에 import 해주면 모든 타입을 정상적으로 표시해 주는 것을 볼 수 있다. (index.html 파일은 수정할 필요가 없다)
getType.js 파일
export default function getType(data) {
return Object.prototype.toString.call(data).slice(8, -1)
}
main.js 파일
import getType from "./getType"
console.log(getType(123))
console.log(getType(false))
console.log(getType(null))
console.log(getType({}))
console.log(getType([]))
test.js 파일
import getType from "./getType"
console.log(getType(false))
크롬 개발자 도구(F12)의 콘솔창
