判断数组的5种方法

akino ... 2021-10-23 17:05 Js
  • 类型判断
小于 1 分钟

由于js中数组属于引用类型,而引用类型都归为object,所以数组是不能通过 typeof 来判断

typeof Array // output: object
1

因此需要通过其它手段来判断

  • 原型判断
  • 实例的父类判断
  • ES5中的 isArray 方法
  • 构造函数判断
  • 使用Object.prototype判断
var arr = [];
console.log(
    arr.__proto__ === Array.prototype, 
    arr instanceof Array, 
    Array.isArray(arr), 
    arr.constructor === Array, 
    Object.prototype.toString.call(arr).slice(8, 13) === 'Array'
);
// output: true true true true true
1
2
3
4
5
6
7
8
9