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

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注