18

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?

2
  • 2
    What do you mean? map((elm, index) => { func(params); })? Commented Dec 10, 2016 at 6:46
  • you can use 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) Commented Dec 10, 2016 at 6:47

2 Answers 2

34

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);

Sign up to request clarification or add additional context in comments.

3 Comments

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.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?
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?
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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.