typeof 연산자
typeof는 변수의 데이터 타입을 반환하는 연산자입니다.
기본형
typeof variable
variable에는 데이터 또는 변수가 들어갑니다. 괄호를 사용해도 됩니다.
typeof (variable)
반환되는 값은 다음과 같습니다.
- undefined : 변수가 정의되지 않거나 값이 없을 때
- number : 데이터 타입이 수일 때
- string : 데이터 타입이 문자열일 때
- boolean : 데이터 타입이 불리언일 때
- object : 데이터 타입이 함수, 배열 등 객체일 때
- function : 변수의 값이 함수일 때
- symbol : 데이터 타입이 심볼일 때
예를 들어
document.write( typeof 3 );
또는
var a = 3;
document.write( typeof a );
는 number 3를 출력합니다.
예제
- 변수의 값을 바꿔가면서 데이터 타입을 출력하는 예제입니다.
var a;
document.write( "typeof a : " + typeof a + "<br>" );
var a = 3;
document.write( "typeof a = 3: " + typeof a + "<br>" );
var a = 'Lorem';
document.write( "typeof a = 'Lorem' : " + typeof a + "<br>" );
var a = true;
document.write( "typeof a = true : " + typeof a + "<br>" );
var a = [ 'Lorem', 'Ipsum', 'Dolor' ];
document.write( "typeof a = [ 'Lorem', 'Ipsum', 'Dolor' ] : " + typeof a + "<br>" );
function a(){};
document.write( "typeof a(){} : " + typeof a + "<br>" );
var a = function(){};
document.write( "typeof a = function(){} : " + typeof a + "<br>" );
var a = Symbol();
document.write( "typeof a = Symbol() : " + typeof a + "<br>" );
로딩 중... 잠시만 기다려주세요.
자바스크립트를 허용해주세요.