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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章