Illie

JS. 타입검사 본문

JAVASCRIPT/자바스크립트

JS. 타입검사

(*ᴗ͈ˬᴗ͈)ꕤ*.゚ 2023. 3. 4. 15:29

1. typeof

function myFunction(){}
class MyClass {}
const str = new String('문자열')

typeof '문자열' --> 'string'
typeof true --> 'boolean'
typeof undefined --> 'undefined'
typeof 123 --> 'number'
typeof Symbol() --> 'symbol'
typeof myFunction --> 'function'

typeof MyClass --> 'undefined'
typeof str --> 'object'
typeof null --> 'object' (공식적으로 인정된 오류)

 

2. instanceof

function Person(name, age) {
    this.name = name;
    this.age = age;
}

const poco = new Person('poco', 99)
const p = {name: 'poco', age: 99}

poco instanceof Person // true
p instanceof Person // false
const arr = []
const func = function() {}
const date = new Date()

arr instanceof Array // true
func instanceof Function // true
date instanceof Date // true

arr instanceof Object // true
func instanceof Object // true
date instanceof Object // true

Object.prototype.toString.call() // [object Undefined]
Object.prototype.toString.call('') // [object String]
Object.prototype.toString.call(new String('')) // [object String]
Object.prototype.toString.call(arr) // [object Array]
Object.prototype.toString.call(func) // [object Function]
Object.prototype.toString.call(date) // [object Date]

'JAVASCRIPT > 자바스크립트' 카테고리의 다른 글

[JS] 클로저  (0) 2023.05.29
JS. 객체의 키 값을 활용하는 방법  (1) 2023.03.19
JS. every / some 개념  (0) 2022.05.01
JS. 테트리스에 시간 추가하기  (0) 2022.04.29
JS. 0422 오답노트 - indexOf  (0) 2022.04.22
Comments