JS判斷數組的方法

判斷一個數組的方法有以下三種:
var obj = [1, 2, 3]

  • Array.isArray(obj)

  • obj instanceof Array 或 obj.constructor === Array

  • Object.prototype.toString.call(obj) === ‘[object Array]’

三種方法的區別?

Array.isArray(obj)
  • 作用:用於確定傳遞的值是否是一個 Array。
  • 參數:obj爲需要檢測的值。
  • 返回值:如果對象是 Array,則爲true; 否則爲false。
obj instanceof Array 或 obj.constructor === Array
  • 作用:用來檢測 constructor.prototype 是否存在於參數 obj 的原型鏈上。
  • obj: 爲要檢測的對象。
  • Array(constructor):某個構造函數。
  • 返回值:如果存在返回true, 不存在則返回false。
obj.constructor === Array
  • 原理同obj instanceof Array
Object.prototype.toString.call(obj)
  • 作用:方法返回一個表示該對象的字符串。
  • 描述:每一個繼承 Object 的對象都有 toString 方法,如果 toString 方法沒有重寫的話,會返回 [Object type],其中 type 爲對象的類型。但當除了 Object 類型的對象外,其他類型直接使用 toString 方法時,會直接返回都是內容的字符串,所以我們需要使用call或者apply方法來改變toString方法的執行上下文。
  • obj: 爲要檢測的對象。
  • 返回值:如果是數組,返回’[object Array]’, 否則返回’[object type]’ (type爲其他類型)。

如果直接調用toString(),則會直接返回對象的內容,如下:

var obj = [1, 2, 3];
obj.toString(); // '1,2,3'

三種方法的優劣勢?

instanceof 與 isArray對比

當檢測Array實例時,Array.isArray 優於 instanceof ,因爲 Array.isArray 可以檢測出 iframe, 而instanceof無法做到。 例如:

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]

// Correctly checking for Array
Array.isArray(arr);  // true
// Considered harmful, because doesn't work though iframes
arr instanceof Array; // false

具體請參考 Array.isArray() – MDN

Array.isArray() 與 Object.prototype.toString.call()對比

Array.isArray()是ES6新增的方法,當不存在 Array.isArray()時 ,可以用 Object.prototype.toString.call() 實現。具體如下:

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

JS判斷數組的方法 是前端面試常考點,在此做下記錄,希望幫助到更多的夥伴~?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章