0

Im new at javascript. Please help me.

Can we create arrays with for loop, without square bracket. Like :

var ar0 = num0
var ar1 = num1
.
.
var ar"i" = num"i"

i cant define like that :

for (i=0;i<5;i++){

var (ar+i) = num+i

}

i know this isnt array but i want create a lot like this. i have to use "for loop"

  • Relevant: ["Variable" variables in JavaScript](https://stackoverflow.com/q/5187530) – VLAZ Oct 29 '21 at 17:33

3 Answers3

0

You can use something like this:

 let result={};
    for (let i=0;i<5;i++){
        result["ar"+i]= `num${i}`;
    }
    console.log(result);

The result will be something like this:

{ ar0: 'num0', ar1: 'num1', ar2: 'num2', ar3: 'num3', ar4: 'num4' }

I hope that's what you are looking for.

ouflak
  • 2,458
  • 10
  • 44
  • 49
akglali
  • 46
  • 4
0

I only see that as a solution :

let ar = Array.from({length:5},(_,i)=>`num${i}`)
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
-1

Use eval built-in function :

for (i=0;i<5;i++){
    eval("var " "ar"+i + "= num+"i)
}
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20