js如何判斷一個對象是數組(函數)


js如何判斷一個對象是數組(函數)

1.typeof操作符 
js如何判斷一個對象是數組

示例:

// 數值
typeof 37 === 'number';

// 字符串
typeof '' === 'string';

// 布爾值
typeof true === 'boolean';

// Symbols
typeof Symbol() === 'symbol';

// Undefined
typeof undefined === 'undefined';

// 對象
typeof {a: 1} === 'object';
typeof [1, 2, 4] === 'object';

// 下面的例子令人迷惑,非常危險,沒有用處。避免使用它們。
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';

// 函數
typeof function() {} === 'function';

從上面的實例我們可以看出,利用typeof除了array和null判斷為object外,其他的都可以正常判斷。

2.instanceof操作符 和 對象的constructor 屬性

這個操作符和JavaScript中面向對象有點關系,了解這個就先得了解JavaScript中的面向對象。因為這個操作符是檢測對象的原型鏈是否指向構造函數的prototype對象的。

 

var arr = [1,2,3,1];
console.log(arr instanceof Array); // true 

var fun = function(){};
console.log(fun instanceof Function); // true 

  

var arr = [1,2,3,1];
console.log(arr.constructor === Array); // true 

var fun = function(){};
console.log(arr.constructor === Function); // true 

  


第2種和第3種方法貌似無懈可擊,但是實際上還是有些漏洞的,當你在多個frame中來回穿梭的時候,這兩種方法就亞歷山大了。由於每個iframe都有一套自己的執行環境,跨frame實例化的對象彼此是不共享原型鏈的,因此導致上述檢測代碼失效

var iframe = document.createElement('iframe'); //創建iframe
document.body.appendChild(iframe); //添加到body中
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // 聲明數組[1,2,3]
alert(arr instanceof Array); // false
alert(arr.constructor === Array); // false

  
4.使用 Object.prototype.toString 來判斷是否是數組

Object.prototype.toString.call( [] ) === '[object Array]'  // true

Object.prototype.toString.call( function(){} ) === '[object Function]'  // true

這里使用call來使 toString 中 this 指向 obj。進而完成判斷  

5.使用 原型鏈 來完成判斷

[].__proto__ === Array.prototype  // true

var fun = function(){}
fun.__proto__ === Function.prototype  // true

  

6.Array.isArray() 

Array.isArray([])   // true

ECMAScript5將Array.isArray()正式引入JavaScript,目的就是准確地檢測一個值是否為數組。IE9+、 Firefox 4+、Safari 5+、Opera 10.5+和Chrome都實現了這個方法。但是在IE8之前的版本是不支持的。 

總結:

綜上所述,我們可以綜合上面的幾種方法,有一個當前的判斷數組的最佳寫法:

var arr = [1,2,3];
var arr2 = [{ name : 'jack', age : 22 }];
function isArrayFn(value){
    // 首先判斷瀏覽器是否支持Array.isArray這個方法
    if (typeof Array.isArray === "function") { 
        return Array.isArray(value);
    }else{
        return Object.prototype.toString.call(value) === "[object Array]";
        // return obj.__proto__ === Array.prototype;
    }
}
console.log(isArrayFn(arr));  // true
console.log(isArrayFn(arr2));  // true        

上述代碼中,為何我們不直接使用原型鏈的方式判斷(兼容性好),而是先判斷瀏覽器支不支持Array.isArray()這個方法,如果不支持才使用原型鏈的方式呢?我們可以從代碼執行效率上看:
js如何判斷一個對象是數組

 

 從這張圖片我們可以看到,Array.isArray()這個方法的執行速度比原型鏈的方式快了近一倍。

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM