Middle
How does Array.from work? What arguments does it accept?
sobes.tech AI
Answer from AI
Array.from is a static method in JavaScript that creates a new array from an iterable or array-like object.
Arguments:
- arrayLike — required. An object with an iterable interface or array-like (e.g., string, NodeList, arguments).
- mapFn — optional. A function to apply to each element before adding it to the new array.
- thisArg — optional. The value to use as
thiswhen executingmapFn.
Example:
const str = 'hello';
const arr = Array.from(str, ch => ch.toUpperCase());
console.log(arr); // ['H', 'E', 'L', 'L', 'O']
Thus, Array.from is convenient for converting iterable objects into arrays with the ability to transform elements.