Introduction:
The Array.from() function is an inbuilt function in JavaScript which creates a new array instance from a given array. In case of a string, every alphabet of the string is converted to an element of the new array instance and in case of integer values, new array instance simple take the elements of the given array.
Syntax 1 :
Array.from(A) A: A can be an array to convert to an array or a string in which every alphabet of the string is to be converted to an element of the new array instance.
Syntax 2 :
Array.from(mapFn,thisArg) Parameters: mapFn (Optional): Map function to call on every element of the array. thisArg (Optional):Value to use as this when executing mapFn.
- Here 2nd column containe int values that are version of the corresponding browser.
Feature Basic support Chrome 45 Edge Yes Firefox 32 Internet Explorer No Opera Yes Safari 9 Chrome for Android Yes Edge mobile Yes Firefox for Android 32 Opera Android Yes iOS Safari Yes
Return value : It returns a new Array instance whose elements are same as the given array. In case of string, every alphabet of the string is converted to an element of the new array instance.
Browser Support:
Examples:
Input : geeksforgeeks Output : Array ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"]
Input : 10, 20, 30 Output : Array [10, 20, 30]
Here as we see that output creats a new array whose content are the same as input in case of integer but in case of string, every alphabet of the string is converted to an element of the new array instance.
Let’s see JavaScript program:
console.log(Array.from( "geeksforgeeks" )); console.log(Array.from([10, 20, 30])); |
Output:
> Array ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"] > Array [10, 20, 30]
Errors and Exceptions:
- If we take complex number as the parameter, it return error because only array and string can be taken as the parameter.
// when complex number is taken as the parameter
// of the function then it return error.
console.log(Array.from(1+2i));
Output:
Error: Invalid or unexpected token
Application:
- Whenever we need to do any opearation with the elements of the array that time we can take help of the Array.from() method in javaScript.
Let’s see JavaScript program:// Here input array is [1,2,3] and output become bouble of each elements.
console.log(Array.from([1, 2, 3], x => x + x));
Output:
> Array [2, 4, 6]
leave a comment
0 Comments