Can I pass additional parameters to JavaScript map() callback function?
I can think of 2 different ways:
Using thisArg
to set an options object as the this
value in the callback:
var numbers = [1,2,3,4,5,6,7,8,9,10];
function callback(element) {
return element + this.add;
};
var mapped = numbers.map(callback, {
add: 10
});
console.log(mapped);
Using .bind()
to set some arguments:
var numbers = [1,2,3,4,5,6,7,8,9,10];
function callback(add, element) {
return element + add;
};
var mapped = numbers.map(callback.bind(null, 10));
console.log(mapped);