在js中的类型检测目前我所知道的是三种方式,分别有它们的应用场景:
1、typeof:主要用于检测基本类型.
1typeof undefined;//=> undefined 2typeof 'a';//=> string 3typeof 1;//=> number 4typeof true;//=> boolean 5typeof {};//=> object 6typeof [];//=> object 7typeof function() {};//=> function 8typeof null;//=> object
2、instanceof:主要用于检测引用类型(左边是对象,右边是函数.根据对象的原形链往上找,如果原形链上有右边函数.prototype,返回true;否则返回false)
1var obj = {}; obj instanceof Object; //=> true; 2var arr = []; arr instanceof Array; //=> true; 3var fn = function() {}; fn instanceof Function; //=> true;
3、Object.prototype.toString.call(sth):由于原形链的检测有漏洞(原型是可以改变的),所以会造成检测结果不准确,所以可以采用此种形式.
1var toString = Object.prototype.toString; 2toString.call(undefined);//=> [object Undefined] 3toString.call(1);//=> [object, Number] 4toString.call(NaN);//=> [object, Number] 5toString.call('a');//=> [object, String] 6toString.call(true);//=> [object, Boolean] 7 8toString.call({});//=> [object, Object] 9toString.call(function() {});//=> [object, Function] 10toString.call([]);//=> [object, Array] 11toString.call(null);//=> [object, Null]