前端面试题:写出尽可能多的方式判断一个变量是否是数组

85 阅读1分钟

判断是否是一个数组:

let arr = [1,2,3]

//判断Array是否在arr的原型链上
arr instanceof Array; //true 
//同上 判断Array的原型对象是否在arr的原型链中
Array.prototype.isPrototypeOf(arr) 
//Array自带的方法
Array.isArray(arr); //true
//用Object.prototype.toString.call() 方法会返回【object Type】
Object.prototype.toString.call(arr) === '[object Array]'//true
//获取arr的原型对象判断是否等于Array的原型对象
Reflect.getPrototypeOf(arr) === Array.prototype//true
//同上
Object.getPrototypeOf(arr) === Array.prototype//true
//同上
arr.__proto__ === Array.prototype
//判断arr的构造函数是不是Array
arr.constructor === Array ; //true
//同上
arr.__proto__.constructor === Array;
const arr = [1,2,3]

arr.toString() // '1,2,3'

Object.prototype.toString.call(arr) // '[object Array]'

Object.prototype.toString ()返回 字符串 '[object Type]', 这里的Type是对象的类型。

用 Object.protoType.toString.call(obj) 可以判断的类型有:

  • '[object Array]'
  • '[object Map]'
  • '[object Set]'
  • '[object Function]'
  • '[object Symbol]'
  • '[object String]'
  • '[object Date]'
  • '[object RegExp]'
  • '[object Error]'
  • '[object Boolean]'
  • '[object Number]'
  • '[object Arguments]'
  • '[object Null]'
  • '[object Undefined]'

其他所有内容、包括用户自定义的类,除非有一个自定义的Symbol.toStringTag ,否则都将返回 '[object object]'