Home > Back-end >  Can we create arrays with for loop, without square bracket in javascript
Can we create arrays with for loop, without square bracket in javascript

Time:10-30

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"

CodePudding user response:

Use eval built-in function :

for (i=0;i<5;i  ){
    eval("var " "ar" i   "= num "i)
}

CodePudding user response:

You can use something like that

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

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

CodePudding user response:

var x = new Array();
for (var i=0;i<5;i  ){
    x.push(i);
}
> x
[ 0, 1, 2, 3, 4 ]
  • Related