I have an array and now I want to execute a function on every element in the array.
I'm trying to use map()
function. The question is, my callback function passed to map()
has its own parameters (not element, index, array).
Can I pass parameters to such a callback function? How?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With