Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass additional parameters to JavaScript map() callback function? [duplicate]

Tags:

javascript

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?

like image 775
jinglei Avatar asked Dec 10 '16 06:12

jinglei


Video Answer


1 Answers

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);
like image 176
Alexander O'Mara Avatar answered Sep 16 '22 20:09

Alexander O'Mara