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

 更新时间:2023年02月10日 09:37:12   作者:下雨打伞干嘛  
本文主要介绍了js怎么判断是否是数组的六种方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

instanceof

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

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

Array.isArray()

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

constructor构造函数

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

a.constructor === Array // true
a.constructor === Object // false

toString

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

isPrototypeOf

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

getPrototypeOf

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

到此这篇关于js怎么判断是否是数组的六种方法小结的文章就介绍到这了,更多相关js 判断是否是数组内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论