JavaScript Array from() Method

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

The from() method of JavaScript is used to return the Array object from any object with a length property or an iterable object.

The syntax is as follows −

Array.from(obj, mapFunction, val)

Above, the parameter obj is the object to convert to an array, mapFunction is a map function to call, val is a value to use as this when executing the mapFunction.

Let us now implement the from() method in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
   <h2>Demo Heading</h2>
   <p id="test"></p>
   <script>
      var arr1 = Array.from("PQRS");
      var arr2 = Array.from("12345");
      document.getElementById("test").innerHTML = arr1 +" and "+arr2;
   </script>
</body>

Output

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
   <h2>Demo Heading</h2>
   <p id="test"></p>
   <script>
      var arr1 = Array.from("PQRS");
      var arr2 = Array.from("%$%#$$#$");
      var arr3 = Array.from("12345");
      document.getElementById("test").innerHTML = arr1 +", "+arr2+" and "+arr3;
   </script>
</body>

Output

raja
Published on 17-Dec-2019 12:04:07
Advertisements