JS數組判斷

判斷是否爲數組

使用typeof

無法區別數組、對象、null

type ans
Undefined “undefined”
Null “object”
Number “number”
String “string”
Boolean “boolean”
Symbol “symbol”
function “function”
其他對象 “object”
typeof NaN === 'number'
typeof Infinity === 'number';

使用instanceof

可以判斷某個構造函數的prototype所指向的對象是否在另一個要檢測的原型鏈上

object instanceof constructor

var a = [];
a instanceof Array; //true

* 目前的 ES 規範中,只能讀取對象的原型而不能改變它,但藉助於非標準的proto
a.__proto__ = {}可以更改,返回false

* 多個窗口產生多個全局環境,不同的全局環境擁有不同的全局對象,從而擁有不同的內
置類型構造函數;

使用constructor

consr a = [];
a.constructor === Array; // true  function Array() {[native code]}

const a = new Array;
a.constructor === Array // true
a.constructor = object;
a.constructor === Array; //false
a instanceof Array // true

* 除了NumberStringBooleanSymbolUndefinedNull的基本數據類
型有隻讀的原生構造函數。對象的 constructor 屬性可被修改

使用objecttoString方法判斷

每個繼承自object的對象都有toString 方法

const a = ['Hello', 'World'];
const o = {x: 'Hello', y: 'World'};
const s = "Hello World";

a.toString() // "Hello World"
o.toString() // "[object object]"
s.toString() // 'Hello World'
Object.prototype.toString.call(a)   // "[object Array]"
Object.prototype.toString.call(o)   // "[object object]"
Object.prototype.toString.call(s)   // "[object String]"

* apply 同理

使用isArray

ES5新增

Array.isArray([]);  //true
Array.isArray([1]); //true
Array.isArray(new Array()); //true
Array.isArray(Array.prototype); //true

* Polyfill (IE9+)

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

* 可檢測iframes

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