您现在的位置是:首页 > 编程语言学习 > 后端编程语言 > 文章正文 后端编程语言

js怎么判断是否是数组的六种方法小结

2023-02-10 10:09:16 后端编程语言

简介本文主要介绍了js怎么判断是否是数组的六种方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

本文主要介绍了js怎么判断是否是数组的六种方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧!

instanceof

主要用来判断某个实例是否属于某个对象所在的原型链上,因此并不能完全分辨出到底是否是数组

  1. let a = [1, 2, 3]; 
  2. console.log(a instanceof Array); // true 
  3. console.log(a instanceof Object); // true 
  4. //从此我们可以看出a既是数组,也是对象 
  5.  
  6. let userInfo = { userName: "zhangsan" }; 
  7. console.log(userInfo instanceof Array); // false 
  8. console.log(userInfo instanceof Object); // true 
  9. //userInfo只是对象,而不是数组 

Array.isArray()

  1. Array.isArray([1,2]); // true 
  2. Array.isArray({name:'zs'}); // false 

constructor构造函数

  1. let a = [1,2]; 
  2. a.__proto__.constructor === Array // true 
  3. a.__proto__.constructor === Object // false 
  4.  
  5. a.constructor === Array // true 
  6. a.constructor === Object // false 

toString

  1. Object.prototype.toString.call([1,2]) // '[object Array]' 
  2. Object.prototype.toString.call({name:'zs'}) // '[object Object]' 

isPrototypeOf

  1. Array.prototype.isPrototypeOf([1,2]) // true 
  2. Array.prototype.isPrototypeOf({name:'zs'})  // false 

getPrototypeOf

  1. Object.getPrototypeOf([1,2]) === Array.prototype // true 
  2. Object.getPrototypeOf({name:'zs'}) === Array.prototype // false 

 

js

站点信息