-2

Okay, I'm not sure what this is called, parsing? Recheck variable?... I'll edit title when I know!

Something simple like this;

var a = b;
var c = d;
var bd = 'hello!';
var e = a + c;

alert(e);
// Want to alert 'Hello!'

In my actual script var b is set on a click event which makes var c equal something like this Staff_Member_TimMarshall whereas a = Staff_Member_ and the onclick sets b = TimMarshall

2 Answers2

1

First, it is invalid to have variable names only be numbers.

Second, you can use eval for this

var a = 'a';
var b = 'b';
var ab = 'hello!';
var c = a + b;

console.log(eval(c));

On a final note, take the use of eval with caution.

See When is JavaScript's eval() not evil?

There is usually a way to avoid using eval and if you give more info in your question, we can attempt a better eval-less solution.

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • 1
    I would not recommend using `eval` for just about anything, especially for a new JS developer. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don't_use_eval_needlessly! – dgrundel Jun 30 '15 at 02:04
  • @dgrundel, right, I included a final note in my answer. Thanks for the heads up – AmmarCSE Jun 30 '15 at 02:05
  • Ah, awesome! You must have been updating your answer when I wrote that. :) – dgrundel Jun 30 '15 at 02:09
1

12 isn't a valid variable name in JS, I believe. Consider putting this into an object:

var obj = {
    a: 1,
    b: 2,
    '12': 'hello!'
};

alert(obj[ '' + obj['a'] + obj['b'] ]);

You also have an issue because a + b === 3, not 12, unless you're doing a string concatenation. So you have to do '' + 1 + 2 to get the string 12.

dgrundel
  • 568
  • 3
  • 7