判断一个对象是不是数组

  • getPrototypeOf(obj)
返回所给对象的原型,如果传入的不是对象那么返回null

  • 用法
console.log( Object.getPrototypeOf( {name:13} ) ); // {},注意类型是对象
console.log( Object.getPrototypeOf( [ 22,44] ) ); // [],注意类型是对象
console.log( Object.getPrototypeOf(13) ); // [Number: 0]
console.log( Object.getPrototypeOf('aa') ); // [String: '']
console.log( Object.getPrototypeOf(false) ); // [Boolean: false]

所以判断一个对象是不是数组方法如下

function isArray(obj){
 return JSON.stringify(Object.getPrototypeOf(obj)) === '[]'
}

  • 为什么不能用String
console.log(String([0,1])) // 0,1 类型为string
console.log(String([])) // null 类型为string

console.log(JSON.stringify([])) // [] 类型为string
console.log(JSON.stringify([0,1])) // [0,1] 类型为string

猜你喜欢

转载自blog.csdn.net/qq1498982270/article/details/88748454