0%

Array-like object

What is array-like object?

Array-like object is an object that has a length property and indexed elements. For example, arguments is an array-like object.

Has indexed access to the elements and a non-negative length property to know the number of elements in it. These are the only similarities it has with an array.
Doesn’t have any of the Array methods like push, pop, join, map, etc.

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 not a function

What is the difference between array and array-like object?

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

Which type in JavaScript is array-like object?

There are many types in JavaScript are array-like object, including:

  1. arguments in a function
  2. NodeList(and other DOM collections)
  3. HTMLCollection

arguments in a function

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)

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

HTMLCollection

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

How to convert array-like object to array?

There are several ways to convert array-like object to array.

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']

Use 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']

Conclusion

  1. Array-like object is an object that has a length property
  2. Array-like object has indexed access to the elements, you access the elements by using arrayLike[n]
  3. Array-like object doesn’t have any of the Array methods like push, pop, join, map, etc.
  4. You can convert array-like object to array by using Array.from(...), ES6 spread operator or Array.prototype.slice.call(...).