JavaScript-typeof 연산자를 사용하여 데이터 타입 확인하기

hannah·2023년 7월 23일
0

JavaScript

목록 보기
7/121

typeof는 변수의 데이터 타입을 반환하는 연산자

활용

  1. 함수 매개변수의 유효성을 검사하거나 변수가 정의되어 있는지 확인 가능
  2. 코드 안에서 액세스하려고 시도하기 전에 변수가 정의되어 있는지 확인 가능
function doSomething(x) {
  if(typeof(x) === 'string') {
    alert('x is a string')
  } else if(typeof(x) === 'number') {
    alert('x is a number')
  }
}

예제

document.writeln(typeof "ABC"); // string

document.writeln(typeof 1); // number
document.writeln(typeof 1.2); // number

document.writeln(typeof { name : "Hailey"});// object
document.writeln(typeof null); // object
document.writeln(typeof [1, 2, 3]); // object

document.writeln(typeof true); // boolean

document.writeln(typeof undeclaredVariable); // undefined

document.writeln(typeof function() {}); // function

document.writeln(typeof 11n); // bigint

typeof "ABC" -문자열은 "string"을 리턴

typeof 1
typeof 1.2
-숫자는 "number"를 리턴

typeof { name : "Hailey"} -객체는 "object"를 리턴

typeof null -null은 "object"를 리턴

typeof [1, 2, 3] -배열은 object의 특수한 한 형태이기 때문에 "object"를 리턴
객체가 배열인지 확인하려면 "isArray()" 함수를 사용

typeof true -true, false 값은 "boolean"을 리턴

typeof undeclaredVariable -미정의된 변수는 "undefined"를 리턴

typeof function() {} -함수는 "function"을 리턴

typeof 11n -BigInt는 "bigint"를 리턴

0개의 댓글