그만큼 JavaScript 유형 연산자 변수 또는 표현식의 데이터 유형을 반환합니다. 피연산자 앞에 배치된 단항 연산자이며 숫자, 문자열, 부울, 객체, 정의되지 않음, 함수 또는 기호와 같은 데이터 유형을 나타내는 문자열을 반환합니다. 일반적으로 처리되는 데이터 유형을 동적으로 결정하여 조건부 논리와 JavaScript 프로그램의 유형 검사를 용이하게 하는 데 사용됩니다.
통사론:
typeof operand // OR typeof (operand)>
기본 데이터 유형
JavaScript의 기본 데이터 유형은 단일 값을 나타내는 기본 데이터 유형입니다. 여기에는 다음이 포함됩니다.
데이터 형식 | 설명 |
---|---|
숫자 | 정수 및 부동 소수점 숫자와 같은 숫자 값을 나타냅니다. |
끈 | 작은따옴표() 또는 큰따옴표()로 묶인 텍스트 데이터를 나타냅니다. |
부울 | 참 또는 거짓 값을 나타냅니다. |
한정되지 않은 | 선언되었지만 값이 할당되지 않은 변수를 나타냅니다. |
없는 | 객체 값이 의도적으로 없음을 나타냅니다. |
상징 | 객체 속성의 키로 사용되는 고유하고 변경할 수 없는 데이터 유형을 나타냅니다. |
BigInt | Number 유형의 제한을 초과하는 큰 정수를 나타냅니다. |
예시 1: 아래 예는 기본 데이터 유형에 대한 typeof 연산자의 결과를 보여줍니다.
자바스크립트 // Define variables with different primitive data types const num = 10; const str = 'Hello'; const bool = true; const undef = undefined; const nul = null; const sym = Symbol('symbol'); const bigInt = 9007199254740991n; // Use typeof operator to determine the data type console.log(typeof num); // Output: 'number' console.log(typeof str); // Output: 'string' console.log(typeof bool); // Output: 'boolean' console.log(typeof undef); // Output: 'undefined' console.log(typeof nul); // Output: 'object' (typeof null is an oddity, // it returns 'object') console.log(typeof sym); // Output: 'symbol' console.log(typeof bigInt);// Output: 'bigint'>
산출
number string boolean undefined object symbol bigint>
예 2: 이 예에서는 값과 유형을 모두 비교한 다음 true 또는 false를 반환하는 '==='(엄격한 동등 비교 연산자)를 사용합니다.
자바스크립트
//Number console.log(typeof 25 === 'number'); console.log(typeof 3.14 === 'number'); console.log(typeof (69) === 'number'); // log base 10 console.log(typeof Math.LN10 === 'number'); console.log(typeof Infinity === 'number'); // Despite being 'Not-A-Number' console.log(typeof NaN === 'number'); // Wrapping in Number() function console.log(typeof Number('100') === 'number');>
설명: 첫 번째 console.log()에서 js는 왼쪽에서 오른쪽으로 컴파일을 시작하고 먼저 'number'인 25의 유형을 계산한 다음 이를 'number'와 비교한 다음 최종적으로 그에 따라 true 또는 false를 반환합니다.
산출
true true true true true true true>
예시 3: 이 예에서는 typeof 연산자를 사용하여 함수 데이터 유형을 비교합니다.
자바스크립트 // function console.log(typeof function () { } === 'function'); //classes too are objects console.log(typeof class C { } === 'function'); console.log(typeof Math.sin === 'function');>
산출
true true true>