Cold_Class Cold_Class - 5 days ago 5
Javascript Question

How to create functions with dynamic content and store them in an object?

I want to create multiple functions that do different things depending on what's written in a data-table and store them in an object for later use.

Let's look at this simple example:



var arrayPl = [];

function myFunction() {
var carNames = ["Volvo", "Nissan"];
var counter = 0;
for (var i in carNames) {
arrayPl[counter] = function() {
alert(carNames[i]);
};
counter++;
}
}

myFunction();
arrayPl[0]();





Here I wanted to create as many functions as there are
car names
and save them in an object
arrayPl
that I could call these functions from later.

Now obviously this example doesn't explain why I would need to do this - but at least it shows my problem, because the first function
arrayPl[0]();
gives me the second car name instead of the first.

Explaining the reason behind this is too complicated for me now and not that important (Dialogs in Adobe LiveCycle) - I just want to know if what I'm asking is possible in general and if so how.

Answer

I prefere this syntax :

var arrayPl = [];

function myFunction() {
  var carNames = ["Volvo", "Nissan"];

  carNames.forEach( function(element, i) {
    arrayPl[i] = function() {
      alert(carNames[i]);
    }
  })
}

myFunction();
arrayPl[0]();

Comments