什么是类数组对象?
类数组对象(Array-like object)是指拥有length
属性且元素可通过索引访问的对象。例如函数的调用参数列表arguments
就是一个典型的类数组对象。
这类对象具有以下特征:
- 具有表示元素数量的非负
length
属性
- 可以通过索引访问元素
类数组对象不具备任何数组方法,例如 push
、pop
、join
、map
等方法均不可用。
1 2 3 4 5 6 7 8 9
| const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3, }; console.log(arrayLike[1]); console.log(arrayLike.length); console.log(arrayLike.push);
|
JavaScript中有哪些类数组对象?
JavaScript 中有多种类型属于类数组对象,包括:
- 函数中的
arguments
对象
- NodeList(以及其他 DOM 集合)
- HTMLCollection
函数的arguments对象
arguments
对象是一个类数组对象,包含函数调用时传入的所有参数
1 2 3 4
| function foo() { console.log(arguments); } foo(1, 2, 3);
|
NodeList(and other DOM collections)
NodeList
是一个类数组对象,通常由DOM查询方法返回,如document.querySelectorAll
。它可以通过索引访问元素,但不具备数组方法。
1 2
| const nodeList = document.querySelectorAll('div'); console.log(nodeList);
|
HTMLCollection
HTMLCollection
是一个类数组对象,通常由DOM查询方法返回,如document.getElementsByClassName
。它也可以通过索引访问元素,但不具备数组方法。
1 2
| const htmlCollection = document.getElementsByClassName('container'); console.log(htmlCollection);
|
如何将类数组对象转换为数组?
虽然类数组对象具有类似数组的特性,但它们并不是数组,因此不能直接使用数组方法。要将类数组对象转换为真正的数组,可以使用以下几种方法:
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);
|
使用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);
|
使用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);
|
总结
- 类数组对象拥有
length
属性且支持索引访问元素,可以通过 arrayLike[n]
的形式访问元素。
- 类数组对象不具备数组方法(如 push、pop、join、map 等)。
- 可以通过
Array.from(...)
、ES6展开运算符
或 Array.prototype.slice.call(...)
将类数组对象转换为真正的数组
数组合类数组对象的比较
类型 |
length属性 |
索引访问 |
有Array.prototype方法 |
Array |
✔️ |
✔️ |
✔️ |
Array-like object |
✔️ |
✔️ |
❌ |