0

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.

Cold_Class
  • 3,214
  • 4
  • 39
  • 82
  • 1
    *"I just want to know if what I'm asking is possible in general."* Yes it is. What you have is the right start, the duplicate explains why it doesn't work quite yet and how to fix it. – Felix Kling Nov 28 '16 at 16:19
  • thx, I didn't find that duplicate before! – Cold_Class Nov 28 '16 at 16:21

1 Answers1

1

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]();
Patrick Ferreira
  • 1,983
  • 1
  • 15
  • 31
  • thx, it solved my question here - unfortunately in my actual problem it's still not working...but I guess I will ask another question again once I figure out what to ask for this time haha – Cold_Class Nov 28 '16 at 16:40
  • hope you'll found your answer ;) – Patrick Ferreira Nov 28 '16 at 17:23
  • I did fortunately - it was just a typo and nothing too major - what I still don't understand is: what's the problem with my original approach? – Cold_Class Dec 01 '16 at 09:05
  • Well, your approach is good too, I just prefer to use `forEach` as [I'm sure that the order will be the same](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/for...in#Utiliser_for...in_et_parcourir_un_tableau) as in the `Array`, I'll already have strange behaviors with `for...in` – Patrick Ferreira Dec 02 '16 at 15:00