javascript - ใช้ลูป for วนผ่านอ็อบเจ็กต์เช่น box0, box1, box2
สมมติว่าฉันมีวัตถุ 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
}
คำตอบ #1
คุณสามารถใช้ eval ได้ แต่โปรดทราบว่าการใช้วิธีนี้อาจมีปัญหาและความเสี่ยงสำหรับคุณ: ดูอันนี้
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
}สนามเด็กเล่น
คำตอบ #2
มีเหตุผลอะไรไหมที่จะไม่เก็บพวกมันทั้งหมดไว้ในอาร์เรย์ตั้งแต่แรก?
// 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
}
