Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo tên biến động (Dynamic Variable Names) trong vòng lặp JavaScript

JavaScript không hỗ trợ trực tiếp tên biến động (variable variables) như PHP $$name. Thay vào đó, dùng Object hoặc Map để lưu cặp key-value động.

Cách KHÔNG khuyến khích (và không hoạt động như mong đợi)


// ❌ KHÔNG THỂ LÀM ĐƯỢC:
for (var i = 0; i < 3; i++) {
  var "var" + i = i * 10; // SyntaxError
}

// ❌ CÁCH CŨ (bài gốc): Gán vào `this` / `window` - Ô NHIỄM GLOBAL
for (var i = 0; i < coords.length; ++i) {
  this["marker" + i] = "add here"; // Tạo window.marker0, marker1...
}
var a = this.marker0; // Truy cập qua window

Vấn đề: Ô nhiễm global scope, xung đột tên, khó debug, không hoạt động trong module/strict mode.

Cách ĐÚNG: Dùng Object / Map

1. Object (Plain Object) – Phổ biến nhất


const markers = {};
for (let i = 0; i < coords.length; i++) {
  markers[`marker${i}`] = "add here"; // Template literal ES6
}

// Truy cập
console.log(markers.marker0); // "add here"
console.log(markers["marker1"]); // "add here"

// Duyệt
Object.keys(markers).forEach(key => {
  console.log(key, markers[key]);
});

2. Map – Tốt hơn cho key động, hiệu năng


const markers = new Map();
for (let i = 0; i < coords.length; i++) {
  markers.set(`marker${i}`, "add here");
}

// Truy cập
markers.get("marker0"); // "add here"

// Duyệt (giữ thứ tự insert)
markers.forEach((value, key) => console.log(key, value));
for (const [key, value] of markers) { ... }

3. Array – Nếu chỉ cần index số


const markers = [];
for (let i = 0; i < coords.length; i++) {
  markers[i] = "add here"; // hoặc markers.push("add here");
}
markers[0]; // "add here"

Ví dụ thực tế: Tạo object từ dữ liệu động


const fields = ["name", "email", "age", "city"];
const user = {};

fields.forEach(field => {
  user[field] = prompt(`Nhập ${field}:`); // Key động từ mảng
});

console.log(user); // { name: "An", email: "a@b.c", age: "25", city: "Hanoi" }

Khi nào thực sự cần "tên biến động"?

Gần như không bao giờ. Cần lưu trữ dữ liệu động → dùng Object/Map. Cần tạo code động → dùng Function constructor hoặc eval (cả 2 đều KHÔNG KHUYẾN NGHỊ).

Tóm tắt

CáchƯu điểmNhược điểmKhuyến nghị
Object {}Đơn giản, JSON serializable, devtools đẹpKey chỉ string/symbol, prototype pollution risk✅ Mặc định
MapKey bất kỳ kiểu, size property, ordered, nhanh thêm/xóa nhiềuKhông JSON native, verbose hơn✅ Key phức tạp, hiệu năng
ArrayIndex số, ordered, methods phong phúChỉ index số✅ Danh sách tuần tự
this[key] / window[key]Tạo biến "thật"Ô nhiễm global, không module-safe, khó debug❌ Không dùng