js类型判断的方式总结
1.typeof
typeof 可以用来判断 string ,number ,boolean,undefined,symbol但是无法判断null ,返回为object ,判断数组和对象的值均为object
typeof(1) // number
typeof('jianshu') // string
typeof(true) // boolean
typeof(undefined) // undefined
typeof(null) // object
typeof([]) // object
typeof({}) // object
instanceof
instanceof运算符希望左操作数是一个对象,右操作数标识对象的类。如果左侧的对象是右侧类的实例,则表达式返回true;否则返回false。
let d = new Date()
d instanceof Date // true
d instanceof Object // true 所有类都是Object的父类
d instanceof Number // false
let arr = [1,2,3]
arr instanceof Array // true
null instanceof Object // false
-
Object.prototype.toString.call()判断对象所属类 。提取返回字符串的倒数第八个到倒数第二个位置。
Object.prototype.toString.call(null) // "[object Null]" Object.prototype.toString.call(null).slice(8,-1) // Null Object.prototype.toString.call(1).slice(8,-1) // Number Object.prototype.toString.call(window).slice(8,-1) //Window 客户端宿主对象 -
Array.isArray() 用来判断是否为数组。
Array.isArray([1,2,3]) // true