typeof
问题:typeof null为object。引用类型数据用typeof来判断的话,除了function会被识别出来之外,其余的都输出object。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| typeof str typeof num typeof array
typeof date typeof func typeof symbol typeof null
typeof test
let message; typeof message
|
instanceof
原理:左边是一个实例对象,右边是一个构造函数,instanceof会检查构造函数的原型对象prototype是否在左边对象的原型链上,有则返回true,否则返回false.
问题:instanceof 可以准确地判断复杂引用数据类型,但是不能正确判断基础数据类型。同时只能判断是否是某个类型,不能检测类型。
1 2 3
| array instanceof Array date instanceof Date func instanceof Function
|
constructor
不能判断null,undefined。
如果创建一个对象,更改它的原型,这种方式也变得不可靠了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| (2).constructor === Number (true).constructor === Boolean ('str').constructor === String ([]).constructor === Array (function() {}).constructor === Function ({}).constructor === Object
function SuperType(){} function SubType(){} SubType.prototype = new SuperType();
let sub = new SubType();
sub.constructor === SubType sub.constructor === SuperType sub.constructor === Object
|
Object.prototype.toString.call()
啥都可以判断,就是写着麻烦
1 2 3 4 5 6 7
| Object.prototype.toString.call(str) === '[object String]' Object.prototype.toString.call(num) === '[object Number]' Object.prototype.toString.call(array) === '[object Array]' Object.prototype.toString.call(date) === '[object Date]' Object.prototype.toString.call(func) === '[object Function]' Object.prototype.toString.call(symbol) === '[object Symbol]' Object.prototype.toString.call(new Error()) === '[object Error]'
|