我們從媽媽、爸爸、祖先三個角度來進行判斷。
根據構造函數判斷(媽媽)
instanceof
判斷一個實例是否屬于某構造函數
let arr = []
console.log(arr instanceof Array) // true
缺點: instanceof 底層原理是檢測構造函數的 prototype 屬性是否出現在某個實例的原型鏈上,如果實例的原型鏈發生變化,則無法做出正確判斷。
let arr = []
arr.__proto__ = function() {}
console.log(arr instanceof Array) // false
constructor
實例的構造函數屬性 constructor 指向構造函數本身。
let arr = []
console.log(arr.constructor === Array) // true
缺點: 如果 arr 的 constructor 被修改,則無法做出正確判斷。
let arr = []
arr.constructor = function() {}
console.log(arr.constructor === Array) // false
根據原型對象判斷(爸爸)
__ proto __
實例的 __ proto __ 指向構造函數的原型對象
let arr = []
console.log(arr.__proto__ === Array.prototype) // true
缺點: 如果實例的原型鏈的被修改,則無法做出正確判斷。
let arr = []
arr.__proto__ = function() {}
console.log(arr.__proto__ === Array.prototype) // false
Object.getPrototypeOf()
Object 自帶的方法,獲取某個對象所屬的原型對象
let arr = []
console.log(Object.getPrototypeOf(arr) === Array.prototype) // true
缺點: 同上
Array.prototype.isPrototypeOf()
Array 原型對象的方法,判斷其是不是某個對象的原型對象
let arr = []
console.log(Array.prototype.isPrototypeOf(arr)) // true
缺點: 同上
原型對象判斷(祖先)
根據 Object 的原型對象判斷
Object.prototype.toString.call()
Object 的原型對象上有一個 toString 方法,toString 方法默認被所有對象繼承,返回 "[object type]" 字符串。但此方法經常被原型鏈上的同名方法覆蓋,需要通過 Object.prototype.toString.call() 強行調用。
let arr = []
console.log(Object.prototype.toString.call(arr) === '[object Array]') // true
這個類型就像胎記,一出生就刻在了身上,因此修改原型鏈不會對它造成任何影響。
let arr = []
arr.__proto__ = function() {}
console.log(Object.prototype.toString.call(arr) === '[object Array]') // true
Array.isArray()
Array.isArray() 是 ES6 新增的方法,專門用于數組類型判斷,原理同上。
let arr = []
console.log(Array.isArray(arr)) // true
修改原型鏈不會對它造成任何影響。
let arr = []
arr.__proto__ = function() {}
console.log(Array.isArray(arr)) // true
總結
以上就是判斷是否為數組的常用方法,相信不用說大家也看出來 Array.isArray 最好用、最靠譜了吧,還是ES6香!