16

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?

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
jinglei
  • 3,269
  • 11
  • 27
  • 46
  • 2
    What do you mean? `map((elm, index) => { func(params); })`? – Andrew Li Dec 10 '16 at 06:46
  • you can use [bind()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) on your callback function to prepend parameters to your callback, ie your function would then have a parameter list like `(arg1, arg2, /*etc*/,element,index,array)` – Patrick Evans Dec 10 '16 at 06:47

2 Answers2

30

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);
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • 1
    Thanks. I've just started to learn Javascript this week. As far as I know, this is a **environment** of a function. For the first solution, I think what you're doing is pass a `this` object to the callback. What is this `this` referring to? – jinglei Dec 10 '16 at 07:00
  • 1
    @Jinglei.Y Usually `this` is used to refer to the object a function is called as a method of. The array map method allows specifying what that `this` object should be, as it is not calling the function as a method this can be very useful. In this case, I just set a specific this value that is my own object. This question goes into more detail on the `this` object: [How does the “this” keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Alexander O'Mara Dec 10 '16 at 07:03
  • Of the 2 I like solution one the best as it avoids the use of bind which seems a bit hacky to me. What are the pros and cons of each approach? – Daniel Nov 05 '19 at 12:57
0

I think you might need to wrap your original function in another callback function, like this:

var array = ['one', 'two', 'skip-a-few', 'three', 'four']

console.log(
    array.map(function (element) {
        return original('other', 'variables', element)
    })
)


// this function doesn't matter, just an example
function original(a, b, c) {
    return a + ' ' + b + ' ' + c
}
gyre
  • 16,369
  • 3
  • 37
  • 47