無論在工作還是面試中,我們都會遇到判斷一個數(shù)據(jù)是否為數(shù)組的需求,今天我們就來總結(jié)一下,到底有多少方法可以判斷數(shù)組,看看哪種方法是最好用、最靠譜的。
我們從媽媽、爸爸、祖先三個角度來進行判斷。
根據(jù)構(gòu)造函數(shù)判斷(媽媽)
instanceof
判斷一個實例是否屬于某構(gòu)造函數(shù)
let arr = []
console.log(arr instanceof Array) // true
缺點: instanceof 底層原理是檢測構(gòu)造函數(shù)的 prototype 屬性是否出現(xiàn)在某個實例的原型鏈上,如果實例的原型鏈發(fā)生變化,則無法做出正確判斷。
let arr = []
arr.__proto__ = function() {}
console.log(arr instanceof Array) // false
constructor
實例的構(gòu)造函數(shù)屬性 constructor 指向構(gòu)造函數(shù)本身。
let arr = []
console.log(arr.constructor === Array) // true
缺點: 如果 arr 的 constructor 被修改,則無法做出正確判斷。
let arr = []
arr.constructor = function() {}
console.log(arr.constructor === Array) // false
根據(jù)原型對象判斷(爸爸)
__ proto __
實例的 __ proto __ 指向構(gòu)造函數(shù)的原型對象
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
缺點: 同上
原型對象判斷(祖先)
根據(jù) Object 的原型對象判斷
Object.prototype.toString.call()
Object 的原型對象上有一個 toString 方法,toString 方法默認被所有對象繼承,返回 "[object type]" 字符串。但此方法經(jīng)常被原型鏈上的同名方法覆蓋,需要通過 Object.prototype.toString.call() 強行調(diào)用。
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 新增的方法,專門用于數(shù)組類型判斷,原理同上。
let arr = []
console.log(Array.isArray(arr)) // true
修改原型鏈不會對它造成任何影響。
let arr = []
arr.__proto__ = function() {}
console.log(Array.isArray(arr)) // true
總結(jié)
以上就是判斷是否為數(shù)組的常用方法,相信不用說大家也看出來 Array.isArray 最好用、最靠譜了吧,還是ES6香!