javascript – "Array-like objects" What are they; how to identify them?

Question:

I am not an expert in English, but reading about ES6 I have found on several occasions that they make mention of Array-like objects (especially when I read about Map , Set , WeakMap , WeakSet ), as in the following context:

Other collections support for-of too

for–of is not just for arrays. It also works on most array-like objects, like DOM NodeLists.

From what little I can understand, I think something like what jQuery returns when they query a list of elements with (example) $('a') .

I understand that an Array is already an object, but what does the term Array-like object refer to? How do I create one? What is the purpose in comparison to an array?

Answer:

An array-like object is an object that resembles an array because it represents a set of elements and has a length property, however it does not directly have the Array.prototype methods that are very useful such as sort , filter , etc.

A very common example of this type of object is arguments which refers to the arguments that are sent to a function:

funtion foo(a, b) {
    console.log(arguments[0]);
}

foo(1, 2); // imprime 1

By not being able to directly invoke any method of Array.prototype what we do is first convert it to an array:

var args = Array.prototype.slice.call(arguments);

The slice method has the ability to work with array-like objects and therefore the conversion is possible.

Other examples are DOM objects obtained through methods like document.getElementsByClassName , known as NodeList . This is an alternative way to convert to array:

var nodeList = document.getElementsByClassName('.tuClase'),
var nodeArray = [].slice.call(nodeList);

Ideally you don't have to create this type of object, it will always be easier to use arrays when you need a collection of elements, this facilitates the integration of a program into a project, since if all functions use arrays there is no need to make conversions. You just have to be aware of what they are and their differences with the arrangements.

Scroll to Top