JavaScript判断数组的六种方法详解

作者:木棉

时间:2026-10-26

浏览:493

本文总结了JavaScript中判断变量是否为数组的六种常用方法。包括使用instanceof运算符、内置的Array.isArray()函数、通过constructor属性、Object.prototype.toString.call()、isPrototypeOf()以及getPrototypeOf()。每种方法各有优劣,适用于不同场景,帮助开发者准确识别数组类型。

文章目录

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

至此,关于JavaScript判断数组类型的六种方法介绍完毕。如需了解更多相关内容,可查阅本站往期文章或继续浏览后续文章,感谢大家的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章