在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]
原文地址:https://www.cnblogs.com/littlebirdlbw/p/6860038.html