Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  53] [ 2]  / answers: 1 / hits: 38841  / 6 Years ago, fri, january 19, 2018, 12:00:00
var strArr = [[1,2,3,4],[1,2,3,4]];
var arr1 = strArr[0].match(/d+/g).map(Number);


I know that the map() method creates a new array with the results of calling a provided function on every element in the calling array. Here as Number is a wrapper object I am not able to understand what's going on.



What I understood is that if I console log removing the map method I get an array of strings whereas including the map method I get an array of numbers.I would like to know how map is able to take each string and converting to number.


More From » arrays

 Answers
7
var arr1 = strArr[0].match(/d+/g).map(Number);


is equivalent to



var arr1 = strArr[0].match(/d+/g).map((str, ind, arr) => Number(str, ind, arr));


The reason Number works despite passing extra arguments in is because it ignores everything but the first argument. You cannot expect every function to behave accordingly, since not all functions ignore everything but the first argument, but in this case it is a convenient shortcut. Another neat example that works well is converting truthy and falsy values to booleans:



var arrBool = arrAny.map(Boolean);

[#55419] Tuesday, January 16, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
abagail

Total Points: 528
Total Questions: 109
Total Answers: 101

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;