JavaScript(JS) array method - from
The Array.from()
method is a static method in JavaScript that creates a new array instance from an array-like or iterable object. It can be used to convert an array-like object (such as a NodeList or arguments object) or an iterable object (such as a Set or Map) into a real array.
Here's the syntax of the Array.from()
method:
Array.from(arrayLike[, mapFunction[, thisArg]]);
arrayLike
is the object to convert to an array. It can be an array-like object or an iterable object.mapFunction
is an optional function to call on each element of the resulting array. The function takes three arguments: the current element being processed, its index, and the array that theArray.from()
method was called on.thisArg
is an optional value to use asthis
when executing themapFunction
.
The Array.from()
method returns a new array instance.
Here's an example of how to use the Array.from()
method:
let arrayLike = {0: 'a', 1: 'b', 2: 'c', length: 3}; let newArray = Array.from(arrayLike); console.log(newArray); // ['a', 'b', 'c']
In this example, we have an object arrayLike
that has three properties (0
, 1
, and 2
) and a length
property of 3
. This object is similar to an array, but it is not actually an array. We use the Array.from()
method to create a real array from this object. The resulting array is ['a', 'b', 'c']
.
Note that the Array.from()
method was introduced in ECMAScript 2015, so it may not be supported by older browsers. If you need to achieve the same functionality in older browsers, you can use the Array.prototype.slice.call()
method or the spread operator (...
).