假设我有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
}发布于 2021-10-16 11:06:46
您可以使用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
}
发布于 2021-10-16 11:56:16
有没有理由一开始就不把它们都放在一个数组中跟踪呢?
// 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
}https://stackoverflow.com/questions/69594943
复制相似问题