判斷是否為一個(gè)數(shù)組
typeof
對(duì)于五種基礎(chǔ)類型(除了null),都可以用typeof來(lái)判斷唤崭,對(duì)于null,array,function,object會(huì)是什么結(jié)果呢拷恨?
<pre>
console.log(typeof null); //object
console.log(typeof []); //object
console.log(typeof {}); //object
console.log(typeof function(){}) //function
</pre>
jQuery.isArray方法的分析
<pre>
jQuery.isArray:
Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
}
</pre>
<pre>
jQuery.type:
function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
}
</pre>
可以看到j(luò)Query.isArray先是試圖調(diào)用原生的isArray方法,若沒(méi)有就調(diào)用jQuery.type方法谢肾。
jQuery.type 先判斷是否為null或undefined是就返回其字符串形式挑随,否則先調(diào)用typeof判斷是否為object或function,是的話調(diào)用class2type[ toString.call(obj) ]可以詳細(xì)判斷勒叠,否則調(diào)用原生typeof
還不明白去看這篇文章
instanceof
用于判斷一個(gè)變量是否為某個(gè)對(duì)象的實(shí)例
<pre>
console.log([] instanceof Array); //true
</pre>
constructor
返回對(duì)創(chuàng)建此對(duì)象的數(shù)組函數(shù)的引用,即返回對(duì)象相對(duì)應(yīng)的構(gòu)造函數(shù)
<pre>
console.log([].constructor === Array); //true
console.log({}.constructor === Object); //true
console.log("string".constructor === String); //true
console.log((123).constructor === Number); //true
console.log(true.constructor === Boolean); //true
</pre>
問(wèn)題
在不同 iframe 中創(chuàng)建的 Array 并不共享 prototype兜挨。
因?yàn)閍rray屬于引用型數(shù)據(jù),傳遞過(guò)程僅傳遞地址眯分,所以用instanceof和constructor判斷的array拌汇,因?yàn)樯婕傲嗽玩湥员仨毷窃诋?dāng)前頁(yè)面聲明的
Object.prototype.toString
這種方法就是剛才的class2type[ toString.call(obj) ]的原理弊决,淘寶的 kissy 也是使用這種方式
涉及prototype和call不懂的快去復(fù)習(xí)
<pre>
Object.prototype.toString.call([]) === "[object Array]" //true
Object.prototype.toString.call({}) === "[object Object]" //true
Object.prototype.toString.call(function(){}) === "[object Function]" //true
Object.prototype.toString.call("1") === "[object String]" //true
</pre>
ES5中isArray
目前瀏覽器基本都支持了ES5噪舀,所以這是判斷數(shù)組的最好方法
<pre>
console.log( Array.isArray([]) ) //true
</pre>
總結(jié)
綜上所述,考慮兼容性和效率問(wèn)題飘诗,以及代碼整潔与倡,判斷是否為數(shù)組的函數(shù)封裝如下:
<pre>
function isArray(o){
return Array.isArray(o) || Object.prototype.toString.call(o) === "[object Array]";
}
</pre>
練習(xí)
原生js實(shí)現(xiàn)一個(gè)判斷數(shù)據(jù)類型的函數(shù)
參考文章:js判斷是否為數(shù)組的函數(shù): isArray()
更多前端雜談和知識(shí)總結(jié)盡在Deacyn的修煉之路