1

I have a drop down menu that has the options 1,2,3,4 (the actual number). I want to create 12 variables a1, a2, a3, a4 and b1, b2, b3, b4 so that c1 = a1 + b1, c2 = a2 + b2, c3=.... Is this possible in javascript?

var a = "a";
var b = "b";
var drop = Number(document.getElementById("drop").value);
for (var i = 0; i <= drop; i++) {
    alert([i]);
    a.name.replace("",i);
    alert();  
};
Jerome
  • 167
  • 1
  • 12

1 Answers1

4

You can have variable variables using the [] syntax. So in the global scope you would use the window object:

var i = 0;
window["a" + i] = 'something'; // same as: var a0 = 'something';
console.log(a0); // something

That said, it would probably be better to group your variables in an object or array, to avoid polluting the global space.

Something like this structure might be ideal:

var data = {
    a : ['a'. 'b', 'c'],
    b : ['d', 'e', 'f'],
    c : ['g', 'h', 'i']
};

console.log( data.a[0] ); // a
console.log( data.b[1] ); // e
console.log( data.c[2] ); // i
MrCode
  • 63,975
  • 10
  • 90
  • 112