JS using map () with a function that has one additional parameter

I am trying to find a way to use the JS Array.prototype.map() functionality with a function that has another additional parameter (if possible at all, and I would like not to overwrite the built-in Array.prototype.map() )., This documentation very good, but does not cover the case of "one or more additional parameters":

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map

 function doOpSingle(elem) { // do something with one array element } var A = ["one", "two", "three", "four"]; var x = A.map(doOpSingle); // this will execute doOpSingle() on each array element 

So far so good. But what if the function in question has two parameters , for example e. a flag that you might want for it (think about bit masks)

 function doOpSingle2(arrelem,flag) { // do something with one array element } var A = ["one", "two", "three", "four"]; var theFlag = util.getMask(); // call external function var y = A.map(doOpSingle2(theFlag)); // this does not work! 

Any decisions should be made without for loops, of course, because we have map() to make our code cleaner and get rid of them!

+6
source share
4 answers

Use anonymous function:

 A.map(function(a) {return doOpSingle2(a,theFlag);}); 
+17
source

A.map(doOpSingle2.bind(null, theFlag))

theFlag will be the first argument:

function doOpSingle2( flag, elem ) { ... }

+15
source

Use an anonymous function.

 var y = A.map(function(x){doOpSingle2(x,theFlag);}); 
+1
source

Edit: Nevermind, for this you really don't need Closure. See Answer Esailija.

There is another option if you are using the Closure library . First you need to rewrite doOpSingle2 so that the flag is first:

 function doOpSingle2(flag, arrelem) { // do something with one array element } 

then you can do

 var y = A.map(goog.partial(doOpSingle2, theFlag)); 

goog.partial partially applies the function, so goog.partial(doOpSingle2, theFlag) equivalent to this function:

 function(arrElem) { return doOpSingle2(theFlag, arrElem); } 

In this particular case, I probably do not recommend this approach, but there may be similar situations where it works well.

+1
source

Source: https://habr.com/ru/post/917306/


All Articles