偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

JS 判斷數(shù)組的方法總結(jié),哪種最靠譜?

開發(fā) 前端
無論在工作還是面試中,我們都會遇到判斷一個數(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香!

責任編輯:武曉燕 來源: 前端YUE
相關推薦

2022-12-01 08:30:10

JavaScript構(gòu)造函數(shù)

2014-02-19 10:49:55

Windows 9

2012-03-27 16:27:20

Pair移動應用

2011-04-29 14:48:50

國產(chǎn)打印機惠普打印機

2020-04-08 17:23:55

電腦檢修濕度

2012-10-22 11:14:05

SDNOpenFlow網(wǎng)絡管理

2016-09-18 10:51:01

JavascriptHtml5移動應用

2013-07-17 12:27:37

2015-01-08 15:36:47

IT運維

2014-07-29 09:33:17

公司郵箱

2017-07-24 12:06:21

互聯(lián)網(wǎng)

2020-02-11 13:52:19

遠程辦公微軟文檔

2011-12-22 09:32:34

虛擬化桌面虛擬化云計算

2020-06-22 11:30:38

密碼數(shù)據(jù)泄露黑客

2019-03-21 12:10:56

騰訊管理年輕化

2014-09-12 21:48:20

海外郵件中繼轉(zhuǎn)發(fā)服務

2014-02-11 09:25:09

2021-04-30 23:46:04

程序員副業(yè)賺錢

2022-02-17 12:13:17

零信任網(wǎng)絡安全網(wǎng)絡攻擊

2015-12-29 10:10:04

私有云虛擬化公共云
點贊
收藏

51CTO技術棧公眾號