1

I wrote a Javascript function and a loop whose role is to call my function, each time with a different parameter. My idea was that the iterator will help me use a different variable each time but obviously this doesn't work. I figured out that my problem is that when the loop calls the function, the parameter is a string rather than an object name. Any way to save that or the idea was flawed from the beginning?

var a0 = [1,2,3];
var a1 = [4,5,6];
var a2 = [7,8,9];

function myFunction (parameter) {instructions;}

for (i=0; i<3; i++)
  myFunction("a"+i);
Adam
  • 13
  • 5
  • why not take an array for the data? – Nina Scholz Aug 25 '20 at 14:37
  • `var things = { a0: ..., a1: ..., a2: ... }; things['a0']` – Taplar Aug 25 '20 at 14:37
  • Sidenote: If it looks like a duck, and walks like a duck, and quacks like a duck, then maybe you want to consider using an array instead of enumerated variables. – Thomas Aug 25 '20 at 15:36
  • I thought about turning all these variables into one array but in the task I'm doing I was already given these three arrays separately and I'd prefer to leave them like that, if possible. I admire the duck comparison though. Thank you all for your help. – Adam Aug 25 '20 at 20:00

1 Answers1

0

You could wrap the arrays in an array and iterate this array.

function myFunction(reference) {
    console.log(...reference);
}

let a0 = [1, 2, 3],
    a1 = [4, 5, 6],
    a2 = [7, 8, 9];

for (const array of [a0, a1, a2]) myFunction(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392