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();  
};
4
  • 1
    Nice idea, but unfortenately not working ; ). There's no way to change a variable name in JS. Building a dynamic object's property name is possible though. Commented Apr 26, 2014 at 16:33
  • 1
    no, and you shouldn't be doing that either. use an array of which you can index the elements using integers. Commented Apr 26, 2014 at 16:33
  • No need to create the variables, an array would suffice for this purpose as in the previous comment Commented Apr 26, 2014 at 16:36
  • Ok, I am using arrays, thank you. Commented Apr 26, 2014 at 17:20

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.