JavaScript中如何正确判断一个变量是否为数组?
Author: 图恩Category: 编程开发Views: 62Published: 2025-11-13 **How to correctly determine if a variable is an array in JavaScript**
**Answer:**
Use the `Array.isArray()` method to check if a variable is an array.
```javascript
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray('hello')); // false
console.log(Array.isArray({})); // false
console.log(Array.isArray(null)); // false
```
**Explanation:**
In JavaScript, arrays are objects, so using `typeof` cannot accurately identify arrays:
```javascript
typeof [1, 2, 3]; // "object"
```
This can lead to incorrect judgments. While `instanceof Array` can be used:
```javascript
[1, 2, 3] instanceof Array; // true
```
However, `instanceof` may return `false` in cross-iframe scenarios due to differences in array constructors across execution contexts, introducing reliability issues.
The `Array.isArray()` method, introduced in ES5, is a static method specifically designed to detect if a value is an array type. It does not rely on constructor functions and behaves consistently across all environments. As such, it is the most reliable method for determining array types. This method correctly identifies arrays regardless of their creation context, making it the preferred approach for array type detection in modern JavaScript.