JavaScript中的数据类型及其检测
1. 数据类型
1.1 基本类型
Number
String
Boolean
Null
Undefined
Symbol
1.2 引用类型
Object
Array
Function
RegExp
Date
2. 类型检测
2.1 typeof
var s = 'Nicholas';var b = true;var i = 22;var u;var n = null;var o = new Object();var f = new Function();console.info(typeof s); // stringconsole.info(typeof b); // booleanconsole.info(typeof i); // numberconsole.info(typeof u); // undefinedconsole.info(typeof n); // objectconsole.info(typeof o); // objectconsole.info(typeof f); // function
typeof
只能检测基本数据类型,对于null
还有一个Bug
2.2 instanceof
result = variable instanceof constructor
instanceof
用于检测某个对象的原型链是否包含某个构造函数的prototype
属性 function C() {}function D() {}var o = new C();o instanceof C // true, Object.getPrototypeOf(o) === C.prototypeo instanceof D // falsefunction Animal() {}function Cat() {}Cat.prototype = new Animal();var b = new Cat();b instanceof Animal // true[1, 2, 3] instanceof Array // true/abc/ instanceof RegExp // true({}) instanceof Object // true(function() {}) instanceof Function // true
instanceof
适用于检测对象,它是基于原型链运作的
2.3 constructor
constructor
属性返回一个指向创建了该对象原型的函数引用,该属性的值是哪个函数本身。
function Animal() {}function Cat() {}function BadCat() {}Cat.prototype = new Animal();BadCat.prototype = new Cat();var a = new Animal();a.constructor === Animal // truevar b = new BadCat();b.constructor === Animal // true
constructor
指向的是最初创建者,而且易于伪造,不适合做类型判断
2.4 toString
Object.prototype.toString.call();({}).toString.call();window.toString.call();toString.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]
几乎十全十美,只是不能检测用户自定义类型
2.5 小结
typeof
只能检测基本数据类型,对于null
还有Buginstanceof
适用于检测对象,它是基于原型链运作的constructor
指向的是最初创建者,而且容易伪造,不适合做类型判断toString
适用于ECMA内置JavaScript类型(包括基本数据类型和内置对象)的类型判断基于引用判等的类型检查都有跨窗口问题,比如
instanceof
和constructor
如果你要判断的是基本数据类型或JavaScript内置对象,使用toString
;如果要判断的是自定义类型,请使用instanceof