javascript
  1. javascript-from

JavaScript from()

Syntax

Array.from(arrayLike[, mapFn[, thisArg]])

Example

const str = 'hello';
const arr = Array.from(str);
console.log(arr); // Output: ['h', 'e', 'l', 'l', 'o']

Output

['h', 'e', 'l', 'l', 'o']


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array.from Example</title>
</head>
<body>

<script>
    // Original string
    const str = 'hello';

    // Use Array.from to convert the string to an array of characters
    const arr = Array.from(str);

    // Log the original string
    document.write("<p>Original String: " + str + "</p>");

    // Log the array of characters
    document.write("<p>Array of Characters: " + arr.join(", ") + "</p>");

    // If you want to display the array using console.log, you can use the following:
    console.log("Array of Characters:", arr);
</script>

</body>
</html>

Try Playground

Explanation

The from() method is a static method that creates a new array from an array-like or iterable object. The from() method can be thought of as a more specialized version of the Array() constructor function.

The first argument to the from() method is the array-like or iterable object that you want to convert to an array. The second optional argument is a mapFn function that can be used to modify the values in the new array. The third optional argument, thisArg, can be used to set the this value inside the mapFn function.

Use

The from() method can be used to convert array-like or iterable objects to an array. This includes things like DOM collections, NodeList objects, and the arguments object.

You can also use the mapFn argument to modify the values in the new array. This can be useful for things like converting values to a different data type or filtering out unwanted values.

Important Points

  • The from() method is a static method of the Array object and can be called directly on the class without creating an instance.
  • The first argument to the from() method must be an array-like or iterable object.
  • The second argument, mapFn, is an optional function that can be used to modify the values in the new array.
  • The thisArg parameter can be used to set the this value inside mapFn.
  • The from() method returns a new array that contains the values from the original array-like or iterable object.

Summary

The from() method is a static method of the Array object that creates a new array from an array-like or iterable object. It can be used to convert various types of objects to arrays, including DOM collections, NodeList objects, and the arguments object. Additionally, you can use the mapFn argument to modify the values in the new array.

Published on: