JS中如何区分数组和对象

方法一:通过调用constructor来识别

{}.constructor    //返回object
[].constructor    //返回Array

方法二:通过instance of来识别

[] instance of Array   //true
{} instance of Array   //false

方法三:通过Object,prototype.toString.call方法来识别

Object.prototype.toString.call([])   //["object Array"]
Object.prototype.toString.call({})   //["object Object"]

方法四:通过ES6中的Array.isArray来识别

Array.isArray([])  //true
Array.isArray({})  //false
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章