0

My problem is best explained in code form.

<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script>
var x = "x";
var y = 1;
var x1 = "something";
alert(x+y);
</script>
</body>
</html>

I would then want it to alert the value of x1, which in this case would be "something". As you can see this obviously doesn't work but how would you do this in JavaScript? It would be much apreciated if you could keep you answer as simple as possible, as I'm new to programming.

EDIT:

I just want to clarify here that the above code isn't actually my project. I was just trying to explain my problem in a simple way so everyone would understand me. I'll put an example of my actual project code below.

value_+x=document.getElementById('square_+x');

Again I know this wont work but would you change this to

value_4=document.getElementById('square_4');

If x happend to be 4?

  • You have a serious misconception here: What you are manipulating by writing `x+y` is the *value* of the variables and **not** their names. – Darkhogg Oct 28 '13 at 16:43
  • See http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name – j08691 Oct 28 '13 at 16:43

2 Answers2

4

If it's a global window variable, you can do

window[x+y];
Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
0

this ll help you provided the documentation as well alert(eval(x+y))

Hisham
  • 455
  • 4
  • 16