เพื่อให้บรรลุเป้าหมายนี้ ต้องเพิ่ม property ให้กับ current scope โดยใช้ this ซึ่งอ้างอิง current scope ในโปรแกรม:
for (var i = 0; i < coords.length; ++i) {
this["marker" + i] = "add here";
}
โค้ดข้างต้นจะสร้างตัวแปรที่คุณต้องการ และเรียกใช้ได้ดังนี้:
var a = this.marker0; alert(a);
จะแสดงข้อความ "add here" ตามที่แสดงข้างต้น
⚠️ ข้อควรระวังและแนวทางที่ดีกว่า
- ไม่แนะนำ: การสร้าง dynamic variable names ด้วย
this[...]หรือeval()— ยากต่อการ debug, maintain, และ minify - แนะนำ: ใช้ Array หรือ Object/Map แทน:
// ใช้ Array (ลำดับมีความหมาย) const markers = []; for (let i = 0; i < coords.length; i++) { markers[i] = "add here"; } console.log(markers[0]); // "add here" // ใช้ Object (key มีความหมาย) const markers = {}; for (let i = 0; i < coords.length; i++) { markers[`marker${i}`] = "add here"; } console.log(markers.marker0); // "add here" // ใช้ Map (key ใดๆ ก็ได้, ordered, performant) const markers = new Map(); for (let i = 0; i < coords.length; i++) { markers.set(`marker${i}`, "add here"); } console.log(markers.get("marker0")); // "add here"