Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS callback using map() with a function that has one additional parameter [duplicate]

I'm trying to find a way to use JS's Array.prototype.map() functionality with a function that has one additional parameter more (if possible at all, and I'd like to avoid having to rewrite built-in Array.prototype.map()). This documentation is very good, but does not cover the "one-or-more-additional-parameter" case:

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, like e. g. a flag you might want to OR to it (think of 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 solutions should do without for loops, of course, because that's why we have map(), to make our code cleaner w/getting rid of these!

like image 526
syntaxerror Avatar asked Jun 03 '12 17:06

syntaxerror


1 Answers

Use an anonymous function:

A.map(function(a) {return doOpSingle2(a,theFlag);});
like image 68
Niet the Dark Absol Avatar answered Sep 30 '22 23:09

Niet the Dark Absol