j s中类型检测方法

在js中的类型检测目前我所知道的是三种方式,分别有它们的应用场景:

1、typeof:主要用于检测基本类型.

typeof undefined;//=> undefined

typeof 'a';//=> string

typeof 1;//=> number

typeof true;//=> boolean

typeof {};//=> object

typeof [];//=> object

typeof function() {};//=> function

typeof null;//=> object

2、instanceof:主要用于检测引用类型(左边是对象,右边是函数.根据对象的原形链往上找,如果原形链上有右边函数.prototype,返回true;否则返回false)

var obj = {}; obj instanceof Object; //=> true; 
var arr = []; arr instanceof Array; //=> true;
var fn = function() {}; fn instanceof Function; //=> true;

3、Object.prototype.toString.call(sth):由于原形链的检测有漏洞(原型是可以改变的),所以会造成检测结果不准确,所以可以采用此种形式.

var toString = Object.prototype.toString;

toString.call(undefined);//=> [object Undefined]

toString.call(1);//=> [object, Number]

toString.call(NaN);//=> [object, Number]

toString.call('a');//=> [object, String]

toString.call(true);//=> [object, Boolean]

toString.call({});//=> [object, Object]

toString.call(function() {});//=> [object, Function]

toString.call([]);//=> [object, Array]

toString.call(null);//=> [object, Null]

 

你可能感兴趣的:(nodejs)