js 判断是不是数组

js yekong 60℃

在JavaScript中,判断一个变量是否是数组可以使用Array.isArray()方法。这是一个简单且可靠的方法,它返回一个布尔值,指示提供的值是否是一个数组。

以下是使用Array.isArray()方法判断变量是否为数组的实例代码:

let arr = [1, 2, 3];
let notArr = { a: 1, b: 2 };

console.log(Array.isArray(arr)); // 输出: true
console.log(Array.isArray(notArr)); // 输出: false

在这个例子中,arr是一个数组,所以Array.isArray(arr)返回true。而notArr不是一个数组,它是一个对象,所以Array.isArray(notArr)返回false

Array.isArray()是ECMAScript 5中引入的,因此在所有现代浏览器中都可用。对于旧版浏览器,可以使用instanceof操作符或者通过判断对象的constructor属性是否等于Array作为替代方法,但这些方法可能不如Array.isArray()准确。

实例代码使用instanceof操作符:

let arr = [1, 2, 3];
let notArr = { a: 1, b: 2 };

console.log(arr instanceof Array); // 输出: true
console.log(notArr instanceof Array); // 输出: false

实例代码检查constructor属性:

let arr = [1, 2, 3];
let notArr = { a: 1, b: 2 };

console.log(arr.constructor === Array); // 输出: true
console.log(notArr.constructor === Array); // 输出: false

请注意,这些替代方法可能在某些特殊情况下不够准确,例如跨iframe或跨窗口的情况。因此,推荐使用Array.isArray()方法进行数组判断。

喜欢 (0)