JavaScript——数据类型检测的方式有哪些

179 阅读2分钟

一、数据类型检测的方式:

1.typeof

console.log(typeof 2);               // number
console.log(typeof true);            // boolean
console.log(typeof 'str');           // string
console.log(typeof []);              // object    
console.log(typeof function(){});    // function
console.log(typeof {});              // object
console.log(typeof undefined);       // undefined
console.log(typeof null);            // object

其中数组、对象、null都会被判断为object,其他判断都正确。

2.instanceof

instanceof可以正确判断对象的类型,其内部运行机制是 判断在其原型链中能否找到该类型的原型

console.log(true instanceof Boolean);                // false 
console.log('str' instanceof String);                // false 
 
console.log([] instanceof Array);                    // true
console.log(function(){} instanceof Function);       // true
console.log({} instanceof Object);                   // true

3.constructor

console.log((true).constructor === Boolean); // true
console.log(('str').constructor === String); // true
console.log(([]).constructor === Array); // true
console.log((function() {}).constructor === Function); // true
console.log(({}).constructor === Object); // true

constructor有两个作用,一是判断数据的类型,二是对象实例通过 constrcutor 对象访问它的构造函数。需要注意,如果创建一个对象来改变它的原型,constructor就不能用来判断数据类型了:

Fn.prototype = new Array();
var f = new Fn();
console.log(f.constructor===Fn);    // false
console.log(f.constructor===Array); // true

4.Object.prototype.toString.call()

Object.prototype.toString.call() 使用 Object 对象的原型方法 toString 来判断数据类型:

var a = Object.prototype.toString;
console.log(a.call(2));
console.log(a.call(true));
console.log(a.call('str'));
console.log(a.call([]));
console.log(a.call(function(){}));
console.log(a.call({}));
console.log(a.call(undefined));
console.log(a.call(null));

同样是检测对象obj调用toString方法,obj.toString()的结果和Object.prototype.toString.call(obj)的结果不一样,这是为什么?

这是因为toString是Object的原型方法,而Array、function等类型作为Object的实例,都重写了toString方法。不同的对象类型调用toString方法时,根据原型链的知识,调用的是对应的重写之后的toString方法(function类型返回内容为函数体的字符串,Array类型返回元素组成的字符串…),而不会去调用Object上原型toString方法(返回对象的具体类型),所以采用obj.toString()不能得到其对象类型,只能将obj转换为字符串类型;因此,在想要得到对象的具体类型时,应该调用Object原型上的toString方法。

二、总结

1.typeof:

注意:数组、对象、null都会被判断为object;

2.instanceof:

返回的是Boolean类型的值,可以判断对象的类型数据,不能准确检测原始类型; eg: A instanceof B 表示B的prototype是否出现 在A的原型链(proto)上;

3.constructor:

作用一:判断数据类型,用来验证除了null和undefined 以外的数据类型的Boolean值; 注意:如果创建一个对象改变了该数据的原型,constructor就不能用来判断数据类型了。

4.Object.protptype.toString.call():

调用了Object原型上的toString()方法来检测当前实例的数据类型;

obj.toString()Object.prototype.toString.call()区别:

toStringObject的原型方法,Array,function,等类型作为Object实例重写toString();所以要得到对象具体数据类型**,应该调用Object原型上的toString()方法。