-1

I've been struggling with a for loop issue. I would like to declare variables using a for loop, such that with each iteration of the for loop I have a new variable with an added index number as the end.

Here's an example of what I mean

for (var i = 1; i <= 8; i++) {

    ingroupProfileText+i = console.log(i);
}

So, with each iteration, the loop is effectively doing the following:

ingroupProfileText1 = console.log(1);
ingroupProfileText2 = console.log(2);
ingroupProfileText3 = console.log(3);
ingroupProfileText4 = console.log(4);
ingroupProfileText5 = console.log(5);
ingroupProfileText6 = console.log(6);
ingroupProfileText7 = console.log(7);
ingroupProfileText8 = console.log(8);

I've looked around and I keep coming across suggestions where some suggest to use an array, eval, or window. I want something locally, and I haven't been able to make it work either way.

Any help would be much appreciated :)

  • What do you mean by "something locally"? "use an array, eval, or window" those are your options and the array is (arguably?) the best. – str Apr 25 '20 at 18:24
  • But that does not make sense. Use array and then extract the data you need from that array. – Aleksandar Đokić Apr 25 '20 at 18:24

2 Answers2

0

Why not use object**[instead of eval which is evil and hard to maintain]** and use the key as a variable.

Just a suggestion for such a dynamic things.

let indexes = {};
for (var i = 1; i <= 8; i++) {
  indexes["ingroupProfileText" + i] = i;
}
const {ingroupProfileText1, ingroupProfileText2} = indexes

console.log({ingroupProfileText1, ingroupProfileText2})

console.log(indexes["ingroupProfileText5"])
xdeepakv
  • 7,835
  • 2
  • 22
  • 32
0

That is not possible. You can't declare variables outside of that loop. You have only 3 options.

  1. Array
  2. Eval
  3. Window

And you should use an array for this purpose.

Aleksandar Đokić
  • 2,118
  • 17
  • 35