0%

Array-like object

什么是类数组对象?

类数组对象(Array-like object)是指拥有length属性且元素可通过索引访问的对象。例如函数的调用参数列表arguments就是一个典型的类数组对象。
这类对象具有以下特征:

  • 具有表示元素数量的非负length属性
  • 可以通过索引访问元素

类数组对象不具备任何数组方法,例如 pushpopjoinmap 等方法均不可用。

1
2
3
4
5
6
7
8
9
const arrayLike = {
0: 'a',
1: 'b',
2: 'c',
length: 3,
};
console.log(arrayLike[1]); // 'b'
console.log(arrayLike.length); // 3
console.log(arrayLike.push); // Uncaught TypeError: arrayLike.push is nota function

JavaScript中有哪些类数组对象?

JavaScript 中有多种类型属于类数组对象,包括:

  1. 函数中的arguments对象
  2. NodeList(以及其他 DOM 集合)
  3. HTMLCollection

函数的arguments对象

arguments对象是一个类数组对象,包含函数调用时传入的所有参数

1
2
3
4
function foo() {
console.log(arguments);
}
foo(1, 2, 3); // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]

NodeList(and other DOM collections)

NodeList是一个类数组对象,通常由DOM查询方法返回,如document.querySelectorAll。它可以通过索引访问元素,但不具备数组方法。

1
2
const nodeList = document.querySelectorAll('div');
console.log(nodeList); // NodeList(3) [div, div, div]

HTMLCollection

HTMLCollection是一个类数组对象,通常由DOM查询方法返回,如document.getElementsByClassName。它也可以通过索引访问元素,但不具备数组方法。

1
2
const htmlCollection = document.getElementsByClassName('container');
console.log(htmlCollection); // HTMLCollection(3) [div.container, div.container, div.container]

如何将类数组对象转换为数组?

虽然类数组对象具有类似数组的特性,但它们并不是数组,因此不能直接使用数组方法。要将类数组对象转换为真正的数组,可以使用以下几种方法:

Array.from(…)

1
2
3
4
5
6
7
8
const arrayLike = {
0: 'a',
1: 'b',
2: 'c',
length: 3,
};
const array = Array.from(arrayLike);
console.log(array); // ['a', 'b', 'c']

使用ES6的扩展运算符(Spread Operator)

1
2
3
4
5
6
7
8
const arrayLike = {
0: 'a',
1: 'b',
2: 'c',
length: 3,
};
const array = [...arrayLike];
console.log(array); // ['a', 'b', 'c']

使用Array.prototype.slice.call(…)

1
2
3
4
5
6
7
8
const arrayLike = {
0: 'a',
1: 'b',
2: 'c',
length: 3,
};
const array = Array.prototype.slice.call(arrayLike);
console.log(array); // ['a', 'b', 'c']

总结

  1. 类数组对象拥有length属性且支持索引访问元素,可以通过 arrayLike[n] 的形式访问元素。
  2. 类数组对象不具备数组方法(如 push、pop、join、map 等)。
  3. 可以通过 Array.from(...)ES6展开运算符Array.prototype.slice.call(...) 将类数组对象转换为真正的数组

数组合类数组对象的比较

类型 length属性 索引访问 有Array.prototype方法
Array ✔️ ✔️ ✔️
Array-like object ✔️ ✔️