首页 > 文章列表 > js如何实现类型判断

js如何实现类型判断

js类型判断
192 2022-08-06

1、判断引用类型和基本类型的类型是不同的,判断基本类型可以用typeof:

typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'

2、typeof对引用类型,除了函数返回function,其他都返回object。但我们开发中数组肯定是要返回array类型的,所以typeof对引用类型来说并不是很适用。判断引用类型一般用instanceof:

var obj = {}
var arr = []
var fun = () => {}
typeof obj // 'object'
typeof arr // 'object'
typeof fun // 'function'
obj instanceof Object // true
arr instanceof Array // true
fun instanceof Function // true

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。