在javascript中咱们一般使用typeof()
来检测变量的类型,可是在一些复杂状况下typeof()
就显得力不从心了,下面咱们来讲说typeof
,constructor
和toString
,使用这三个进行类型的检测.javascript
typeof
检测js中的基本类型仍是能够的.java
var num = 1; typeof(num) // number var str = 'hello'; typeof(str); // string var bool = true; typeof(bool); // boolean
对于undefined
和null
就比较特殊了,数组
typeof(undefined); // undefined typeof(null); // object
对于函数、数组函数
function a(){}; typeof(a); // function var arr = []; typeof(arr); // object
对于下面的检测就比较混乱了:this
typeof new Boolean(true) === 'object'; typeof new Number(1) ==== 'object'; typeof new String("abc") === 'object'; typeof new Date() === 'object';
该函数用来查看对象的构造函数prototype
var bool = true; console.log(bool.constructor == Boolean);// true var num = 1; console.log(num.constructor == Number); // true var str = 'hello'; console.log(str.constructor == String); // true
这里须要注意的是:
对于 undefined
和 null
,不可以使用 construcor
检测.code
使用toString
检测,必须使用Object.prototype.toString()
,
先来看看这个东东输出什么鬼:对象
console.log(Object.prototype.toString()); // [object Object]
那么如何使用toString()
来进行检测呢?这里使用 call()
来改变this
的指向,ip
var bool = true; console.log(Object.prototype.toString.call(bool)); // [object Boolean] var num = 1; console.log(Object.prototype.toString.call(num)); // [object Number] var str = 'hello'; console.log(Object.prototype.toString.call(str)); // [object String] var arr = []; console.log(Object.prototype.toString.call(arr)); // [object Array] var a = undefined; console.log(Object.prototype.toString.call(a)); // [object Undefined] var b = null; console.log(Object.prototype.toString.call(b)); // [object Null]
能够看出 使用Object.prototype.toString.call()
来检测 是比较完美的.推荐使用.原型链
检测某个实例是否在某个对象的原型链上 原型链__proto__,
var c = []; console.log(c instanceof Object); //true var d = 123; // 这些 普通类型 并非对象 console.log(d instanceof Object); //false var str = 'hello'; // 不是对象 console.log(str instanceof Object); //false var num = new Number(123); console.log(num instanceof Object);