使用 for 循环遍历 box0、box1、box2 等对象

Loop through objects like box0, box1, box2 with a for loop

假设我有 5 个对象,box0 box1 box2 box3 box4 box5

有没有办法在for循环中访问他们的成员? 我试过这种方式,但它不起作用,因为 box${i} 是一个字符串

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

您可以使用 eval 但请注意,使用此方法可能会给您带来一些问题和风险:请参阅 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
   }

Playground

是否有理由不首先将它们全部跟踪到一个数组中?

// 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
}