[javascript] 객체가 원시 타입인지 확인하는 방법
1. typeof
연산자
JavaScript에서는 typeof
연산자를 사용하여 값의 데이터 타입을 확인할 수 있습니다. 원시 타입은 'number'
, 'string'
, 'boolean'
, 'undefined'
, 'symbol'
, 그리고 null
이며, 객체는 'object'
입니다.
typeof 5 // 'number'
typeof 'hello' // 'string'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof Symbol('sym') // 'symbol'
typeof null // 'object'
typeof {} // 'object'
typeof [] // 'object'
2. instanceof
연산자
instanceof
연산자는 객체의 생성자 함수를 사용하여 객체의 타입을 확인합니다. 하지만 null
과 undefined
는 instanceof
연산자로 확인할 수 없습니다.
5 instanceof Number // false
'hello' instanceof String // false
true instanceof Boolean // false
undefined instanceof Object // false
null instanceof Object // false
{} instanceof Object // true
[] instanceof Array // true
3. Object.prototype.toString
메서드
Object.prototype.toString
메서드는 객체의 타입을 확인하는 데 사용될 수 있습니다.
Object.prototype.toString.call(5) // '[object Number]'
Object.prototype.toString.call('hello') // '[object String]'
Object.prototype.toString.call(true) // '[object Boolean]'
Object.prototype.toString.call(undefined) // '[object Undefined]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call([]) // '[object Array]'
각각의 방법은 객체가 원시 타입인지 확인하는 데 사용될 수 있지만, typeof
연산자가 가장 일반적으로 사용되는 방법입니다.
참고문헌:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString