06. Array-like Objects

Some objects in JavaScript are Array-like, they are almost Arrays, but don’t have any of the Array methods.

  • arguments object

  • NodeList returned by document.querySelectorAll();

Array-like objects has length property and index-based access to properties but it isn’t an instance of Array and does not have corresponding Array methods like map().

const args = (function() {
  return arguments;
})("a", "b");
args.length; // 2
args[0]; // 'a'
args instanceof Array; // false
args.map; // undefined

Array.prototype.slice

For many complex operations, you need to convert Array-like objects to Arrays first. That is achieved via Array.prototype.slice(). This method copies the elements of its receiver into a new Array:

const arr = ["a", "b"];
const copy = arr.slice(); // [ 'a', 'b' ]
arr.slice() === arr; // false

Using this method possible to convert any Array-like object to an Array:

function format(pattern) {
  // params start at arguments[1], skipping `pattern`
  var params = Array.prototype.slice.call(arguments, 1);
  return params;
}
console.log(format("a", "b", "c")); // ['b', 'c']

The rest parameters could replace all usage of arguments.

Array.from

ES6 has Array.from(), a simpler way of converting Array-like objects to Arrays:

const domLinks = document.querySelectorAll("a[href]");
const links = Array.from(domLinks);
links.map(link => link.href);

Array.from() позволяет вам создавать массивы из:

  • Array-like объектов (объектов со свойством length и элементами по индексным ключам)

  • итерируемых объектов (объектов, из которых вы можете достать их элементы, например Map или Set).

Array.from() имеет необязательный параметр mapFn, который позволяет вам выполнять функцию map для каждого элемента создаваемого массива (или его подкласса). Проще говоря, вызов Array.from(obj, mapFn, thisArg) эквивалентен цепочке Array.from(obj).map(mapFn, thisArg), за исключением того, что он не создаёт промежуточного массива.

Last updated