JavaScript中的数据类型及其检测

JavaScript中的数据类型及其检测

1. 数据类型

1.1 基本类型

  1. Number

  2. String

  3. Boolean

  4. Null

  5. Undefined

  6. Symbol

1.2 引用类型

  1. Object

  2. Array

  3. Function

  4. RegExp

  5. 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); // string
console.info(typeof b); // boolean
console.info(typeof i); // number
console.info(typeof u); // undefined
console.info(typeof n); // object
console.info(typeof o); // object
console.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.prototype
o instanceof D // false

function 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 // true
var 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 小结

  1. typeof只能检测基本数据类型,对于null还有Bug

  2. instanceof适用于检测对象,它是基于原型链运作的

  3. constructor指向的是最初创建者,而且容易伪造,不适合做类型判断

  4. toString适用于ECMA内置JavaScript类型(包括基本数据类型和内置对象)的类型判断

  5. 基于引用判等的类型检查都有跨窗口问题,比如instanceof和constructor

如果你要判断的是基本数据类型或JavaScript内置对象,使用toString;如果要判断的是自定义类型,请使用instanceof

参考

  1. w3cPlus - JavaScrit的变量:如何检测变量类型

  2. JavaScript高级程序设计(第3版)

关键字:JavaScript, object, function, typeof


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部