类数组如何转换成数组

类数组(array-like)拥有 length 属性、按索引读写元素,但不是真正的数组,不能调用 forEach、map 等数组方法。常见的类数组有:arguments、NodeList、HTMLCollection、{ 0:'a', 1:'b', length: 2 } 等。

// 创建一个类数组对象
const alo = { 0: 'a', 1: 'b', 2: 'c', length: 3 };

1. Array.from()

Array.from(alo);                  // ['a', 'b', 'c']
Array.from(document.querySelectorAll('div')); // NodeList -> Array

支持第二个映射函数:

Array.from({ length: 3 }, (_, i) => i + 1); // [1, 2, 3]

2. Array.prototype.slice.call()

const arr = Array.prototype.slice.call(alo);
console.log(arr); // ['a', 'b', 'c']

也可简写为 [].slice.call(alo)。

3. 扩展运算符 ...

ES6 起最简洁的写法,但要求对象可迭代(含 Symbol.iterator)。

const arr = [...alo];                // 普通对象不可迭代,报 TypeError
const arr2 = [...document.querySelectorAll('div')]; // NodeList 可迭代
const arr3 = [...'abc'];             // 'abc' -> ['a', 'b', 'c']

补充:对于 arguments,可直接 [...arguments];NodeList 多数浏览器已实现 Symbol.iterator,扩展运算符可用;纯对象型类数组(如 {0:'a', length:1})只能用 Array.from 或 slice.call 转换。

来源整理自:vue3js.cn 面试官系列