判断数组的方式有多种,以下是最常用的方法:
一、JavaScript 中的判断方法
1. Array.isArray() (推荐)
Array.isArray([]); // true
Array.isArray({}); // false
Array.isArray("array"); // false
2. instanceof
[] instanceof Array; // true
3. Object.prototype.toString.call()
Object.prototype.toString.call([]) === "[object Array]"; // true
4. constructor
[].constructor === Array; // true
5. Array.isPrototypeOf()
Array.prototype.isPrototypeOf([]); // true
二、TypeScript 中的类型守卫
function isArray(value: unknown): value is any[] {
return Array.isArray(value);
}
三、框架/库提供的方法
Lodash
_.isArray([]); // true
jQuery
jQuery.isArray([]); // true
四、各种方法的比较
| 方法 | 优点 | 缺点 |
|---|---|---|
Array.isArray() | ES5标准,跨iframe安全 | 旧浏览器需要polyfill |
instanceof | 简单直观 | 跨iframe时可能失效 |
Object.prototype.toString.call() | 最可靠,兼容性好 | 代码较长 |
constructor | 简单 | 可被修改,不可靠 |
五、特殊案例处理
// 检查是否为空数组
const isEmptyArray = arr => Array.isArray(arr) && arr.length === 0;
// 检查是否为类数组对象
function isArrayLike(obj) {
return obj != null &&
typeof obj === 'object' &&
typeof obj.length === 'number' &&
obj.length >= 0;
}
// NodeList、HTMLCollection等类数组
Array.isArray(document.querySelectorAll('div')); // false
Array.from(document.querySelectorAll('div')); // 转换为数组
六、最佳实践建议
- 现代开发:首选
Array.isArray() - 兼容性要求高:使用
Object.prototype.toString.call() - 框架环境:使用框架提供的方法(如 Vue、React 的检查工具)
- 避免使用:
typeof []; // "object"(不准确)
[].length !== undefined; // 误判类数组对象
七、示例代码
// 综合判断函数
function checkArray(value) {
// 优先使用现代API
if (typeof Array.isArray === 'function') {
return Array.isArray(value);
}
// 回退方案
return Object.prototype.toString.call(value) === '[object Array]';
}
// 使用示例
console.log(checkArray([])); // true
console.log(checkArray({})); // false
console.log(checkArray("array")); // false
console.log(checkArray(new Array())); // true
总结:在大多数情况下,直接使用 Array.isArray() 是最佳选择,它是ES5标准方法,性能好且语义清晰。