Home > Software design >  Loop through objects like box0, box1, box2 with a for loop
Loop through objects like box0, box1, box2 with a for loop

Time:10-17

Let's say I have 5 objects, box0 box1 box2 box3 box4 box5.

Is there any way to access their members in a for loop? I tried this way, but it wouldn't work because box${i}is a string

 let boxCoordinates: Array<Coordinate> = [];
 for(let i=0;i<5;i  )
     {
         boxCoordinates.push(`box${i}`.current.getBoundingClientRect) //box0, box1, box2, box3, box4
     }

CodePudding user response:

You can use eval but note that using this method may has some problems and risk for you: see this

var box0 = {index:1};

for(let i=0;i<1;i  )
   {
       let d = eval(`box${i}`);
       console.log(typeof d);//object
       console.log(d.index) //1
   }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Playground

CodePudding user response:

Is there a reason to not have them all tracked in an array in the first place?

// Assuming their defined somewhere else
const boxArray = [box1, box2, box3, box4, box5];
for (let i =0; i < boxArray.length; i   ) { 
  const box = boxArray[i];
  // Do what you need with box now
}
  • Related