作用:使用typeof操作符来检测变量的数据类型
实例:
typeof "John" // 返回 string
typeof 3.14 // 返回 number
typeof false // 返回 boolean
typeof [1,2,3,4] // 返回 object
typeof {name:'John', age:34} // 返回 object
null
typeof null 返回object
null是一个只有一个值的特殊类型,表示一个空对象引用
undefined
typeof undefined返回undefined
undefined是一个没有设置值的变量
undefined和null的区别
null 和 undefined 的值相等,但类型不等:
typeof undefined // undefined
typeof null // object
null === undefined // false
null == undefined // true
instanceof
可通过 instanceof 操作符来判断对象的具体类型
instanceof
适用于检测对象,它是基于原型链运作的。对基本数据类型检测不起作用,因为基本数据没有原型链。
(1)检测内部对象
arr = [1,2,3];
if(arr instanceof Array){
document.write("arr 是一个数组");
} else {
document.write("arr 不是一个数组");
}
(2)检测任意类型对象
// 比如直接原型关系
function Animal () {};
var a = new Animal();
a instanceof Animal; // => true
constructor属性:返回一个创建了该对象原型的函数引用;
constructor不适合判断变量类型,因为它是一个属性,容易伪造
constructor只能用于检测对象,对基本类型调用会抛出异常。
null.constructor; // => TypeError
undefined.constructor; // => TypeError
toString:最简单的数据类型检测方法,但是因为toString属性定义在Object.prototype上
,所以所有的对象都有toString方法,默认情况下,都会返回[object object];但可以通过
.call()方法来解决
Object.prototype.toString.call([]); // => [object Array]
Object.prototype.toString.call({}); // => [object Object]
Object.prototype.toString.call(''); // => [object String]
Object.prototype.toString.call(new Date()); // => [object Date]
Object.prototype.toString.call(1); // => [object Number]
Object.prototype.toString.call(function () {}); // => [object Function]
Object.prototype.toString.call(/test/i); // => [object RegExp]
Object.prototype.toString.call(true); // => [object Boolean]
Object.prototype.toString.call(null); // => [object Null]
Object.prototype.toString.call(); // => [object Undefined]
typeof
只能检测基本数据类型,对于null
还有Bug;instanceof
适用于检测对象,它是基于原型链运作的;constructor
指向的是最初创建者,而且容易伪造,不适合做类型判断;toString
适用于ECMA内置JavaScript类型(包括基本数据类型和内置对象)的类型判断;- 基于引用判等的类型检查都有跨窗口问题,比如
instanceof
和constructor
。
总之,如果你要判断的是基本数据类型或JavaScript内置对象,使用toString
; 如果要判断的是自定义类型,请使用instanceof
。