方法一:使用Array.isArray():是一个内置的JavaScript方法,用于检查一个变量是否为数组
Array.isArray() 是一个内置函数,用于确定给定的值是否为数组。它返回一个布尔值,如果给定的值是数组,则返回true,否则返回false。
const array = [1, 2, 3];
const notArray = 'not an array'
console.log(Array.isArray(array)); // 输出:true
console.log(Array.isArray(notArray)); // 输出:false
方法二:使用instanceof运算符:用于检测构造函数的 prototype 属性是否存在于某个对象的原型链上。
instanceof 运算符用于检测对象是否属于特定类。在 JavaScript 中,数组是通过 Array 类型定义的。因此,我们可以使用 instanceof 运算符来检测一个值是否为数组。
const array = [1, 2, 3];
const notArray = 'not an array'
console.log(array instanceof Array); // 输出:true
console.log(notArray instanceof Array); // 输出:false
方法三:使用Array.prototype.constructor
JavaScript 中的数组对象继承自 Array.prototype。每个数组都有一个 constructor 属性,指向创建该数组的构造函数 Array()。因此,我们可以通过检查数组的 constructor 属性来确定一个值是否为数组。
const array = [1, 2, 3];
const notArray = 'not an array'
console.log(array.constructor === Array); // 输出:true
console.log(notArray.constructor === Array); // 输出:false
方法四: 使用 Object.prototype.toString.call(): 这种方法可以获取一个对象的准确类型
let arr = [1, 2, 3];
console.log(Object.prototype.toString.call(arr) === '[object Array]'); // 输出: true
方法五: 使用 Array.prototype.isPrototypeOf(): 这个方法用于测试一个对象是否存在于另一个对象的原型链上
let arr = [1, 2, 3];
console.log(Array.prototype.isPrototypeOf(arr)); // 输出: true