JavaScript判斷數(shù)組的方法總結(jié)與推薦
前言
無論在工作還是面試中,我們都會(huì)遇到判斷一個(gè)數(shù)據(jù)是否為數(shù)組的需求,今天我們就來總結(jié)一下,到底有多少方法可以判斷數(shù)組,看看哪種方法是最好用、最靠譜的。
我們從媽媽、爸爸、祖先三個(gè)角度來進(jìn)行判斷。
根據(jù)構(gòu)造函數(shù)判斷(媽媽)
instanceof
判斷一個(gè)實(shí)例是否屬于某構(gòu)造函數(shù)
let arr = [] console.log(arr instanceof Array) // true
缺點(diǎn): instanceof 底層原理是檢測構(gòu)造函數(shù)的 prototype 屬性是否出現(xiàn)在某個(gè)實(shí)例的原型鏈上,如果實(shí)例的原型鏈發(fā)生變化,則無法做出正確判斷。
let arr = [] arr.__proto__ = function() {} console.log(arr instanceof Array) // false
constructor
實(shí)例的構(gòu)造函數(shù)屬性 constructor 指向構(gòu)造函數(shù)本身。
let arr = [] console.log(arr.constructor === Array) // true
缺點(diǎn): 如果 arr 的 constructor 被修改,則無法做出正確判斷。
let arr = [] arr.constructor = function() {} console.log(arr.constructor === Array) // false
根據(jù)原型對象判斷(爸爸)
__ proto __
實(shí)例的 __ proto __ 指向構(gòu)造函數(shù)的原型對象
let arr = [] console.log(arr.__proto__ === Array.prototype) // true
缺點(diǎn): 如果實(shí)例的原型鏈的被修改,則無法做出正確判斷。
let arr = [] arr.__proto__ = function() {} console.log(arr.__proto__ === Array.prototype) // false
Object.getPrototypeOf()
Object 自帶的方法,獲取某個(gè)對象所屬的原型對象
let arr = [] console.log(Object.getPrototypeOf(arr) === Array.prototype) // true
缺點(diǎn): 同上
Array.prototype.isPrototypeOf()
Array 原型對象的方法,判斷其是不是某個(gè)對象的原型對象
let arr = [] console.log(Array.prototype.isPrototypeOf(arr)) // true
缺點(diǎn): 同上
根據(jù) Object 的原型對象判斷(祖先)
Object.prototype.toString.call()
Object 的原型對象上有一個(gè) toString 方法,toString 方法默認(rèn)被所有對象繼承,返回 "[object type]
" 字符串。但此方法經(jīng)常被原型鏈上的同名方法覆蓋,需要通過 Object.prototype.toString.call() 強(qiáng)行調(diào)用。
let arr = [] console.log(Object.prototype.toString.call(arr) === '[object Array]') // true
這個(gè)類型就像胎記,一出生就刻在了身上,因此修改原型鏈不會(huì)對它造成任何影響。
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
修改原型鏈不會(huì)對它造成任何影響。
let arr = [] arr.__proto__ = function() {} console.log(Array.isArray(arr)) // true
總結(jié)
以上就是判斷是否為數(shù)組的常用方法,相信不用說大家也看出來 Array.isArray 最好用、最靠譜了吧,還是ES6香!
到此這篇關(guān)于JavaScript判斷數(shù)組方法的文章就介紹到這了,更多相關(guān)JavaScript判斷數(shù)組方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js中Array.forEach跳出循環(huán)的方法實(shí)例
相信大家都知道forEach適用于只是進(jìn)行集合或數(shù)組遍歷,for則在較復(fù)雜的循環(huán)中效率更高,下面這篇文章主要給大家介紹了關(guān)于js中Array.forEach跳出循環(huán)的相關(guān)資料,需要的朋友可以參考下2021-09-09js AppendChild與insertBefore用法詳細(xì)對比
本篇文章主要是對js中AppendChild與insertBefore的用法進(jìn)行了詳細(xì)的對比。需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12JavaScript隊(duì)列、優(yōu)先隊(duì)列與循環(huán)隊(duì)列
這篇文章主要為大家詳細(xì)介紹了JavaScript隊(duì)列、優(yōu)先隊(duì)列與循環(huán)隊(duì)列的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11