JavaScript判断数组的五种常用方法详解
本文详细介绍JavaScript中判断变量是否为数组的五种方法:使用内置的Array.isArray()、instanceof运算符、对象的constructor属性、Object.prototype.toString.call()以及原型链上的isPrototypeOf()。通过具体代码示例对比各方法的适用场景与返回值,帮助开发者准确识别数据类型。
JavaScript判断数组的五种常用方法详解
本文整理了可用于验证数据类型的多种方案。
let a = [1,2,3,4,5,6];
let b = [
{name: '张飞', type: 'tank'},
{name: '关羽', type: 'soldier'},
{name: '刘备', type: 'shooter'},
];
let c = 123;
let d = 'www';
let e = {name: '安琪拉', type: 'mage'};
使用Array.isArray()检测
第一种方法:使用Array.isArray()。
Array.isArray()函数用于检测传入参数是否为数组类型。若参数为数组,则返回true;否则返回false。
console.log(Array.isArray(a)); // true
console.log(Array.isArray(b)); // true
console.log(Array.isArray(c)); // false
console.log(Array.isArray(d)); // false
console.log(Array.isArray(e)); // false
使用instanceof运算符检测
第二种方法:使用instanceof运算符。
instance运算符用于检测实例对象是否属于某个构造函数的原型链中。
console.log(a instanceof Array); // true
console.log(b instanceof Array); // true
console.log(c instanceof Array); // false
console.log(d instanceof Array); // false
console.log(e instanceof Array); // false
该运算符同样适用于判断普通对象。
console.log(e instanceof Object); // true
判断数组的本质是检测Array.prototype属性是否存在于变量(如a、b)的原型链上。由于a和b均为数组,它们拥有Array.prototype属性,因此返回true。
通过constructor属性判断
第三种方法:通过对象构造函数的constructor属性判断。
Object的每个实例都包含一个constructor属性,该属性保存着创建当前对象的构造函数。

console.log(a.constructor === Array); // true
console.log(b.constructor === Array); // true
以下示例包含对其他数据类型的验证。
console.log(c.constructor === Number); // true
console.log(d.constructor === String); // true
console.log(e.constructor === Object); // true
使用Object.prototype.toString.call()判断
第四种方法:通过Object.prototype.toString.call()判断。
该方法通过原型链查找并调用toString方法,返回标准的类型字符串。
console.log(Object.prototype.toString.call(a) === '[object Array]'); // true
console.log(Object.prototype.toString.call(b) === '[object Array]'); // true
以下示例包含对其他数据类型的验证。
console.log(Object.prototype.toString.call(c) === '[object Number]'); // true
console.log(Object.prototype.toString.call(d) === '[object String]'); // true
console.log(Object.prototype.toString.call(e) === '[object Object]'); // true
通过isPrototypeOf()方法判断
第五种方法:通过对象原型链上的isPrototypeOf()判断。
Array.prototype是Array构造函数的原型对象,其中包含isPrototypeOf()方法。该方法用于测试一个对象是否存在于另一个对象的原型链上。
console.log(Array.prototype.isPrototypeOf(a)); // true
console.log(Array.prototype.isPrototypeOf(b)); // true
console.log(Array.prototype.isPrototypeOf(c)); // false
console.log(Array.prototype.isPrototypeOf(d)); // false
console.log(Array.prototype.isPrototypeOf(e)); // false
总结。
本文介绍了利用JS判断元素是否为数组的多种实现方式,更多相关JS判断数组的内容请搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!
JavaScript异步发送HTTP请求时怎么优雅地处理错误
2026-11-05 17:10:44
5款主流JS在线运行工具对比:CodePen、JSFiddle与StackBlitz怎么选
2026-11-05 17:04:04
JavaScript入门书籍避坑:这些书不适合初学者
2026-11-05 16:31:15
JS使用Math.round实现保留两位小数的原理与代码
2026-11-05 15:35:55
JavaScript 原生 Date 对象怎么实现日期加减
2026-11-05 14:30:00
