1

I've got this snippet of code..

var test_a = "<?php echo $a ?>"
console.log (test_a);

This shows 1.576.21422 which is correct.

But when I try the same here I don't get the result I was expecting.. I get the variable name.

I know in this test fieldData[0] = 'a'

    console.log ("test_" + fieldData[0])

Instead of showing 1.576.21422 I get test_a

Can someone point me in the right direction for this... Thanks

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Rocket
  • 1,065
  • 2
  • 21
  • 44
  • That may help you : http://stackoverflow.com/a/26020014/2324107 . I actuallythink it's a duplicate but since my close vote equal an instant close and I am not sure, ill leave it open – Karl-André Gagnon Nov 10 '14 at 15:12
  • http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript/ – Hackerman Nov 10 '14 at 15:25

1 Answers1

2

As it is you're outputting a string concatenated with another string. Your goal is to turn the resulting string into a variable. You could make the variable a member of a particular object (or the window object) and access the value of that member using the notation object[ "key" ].

Warning -- Even though eval( .... ) would work, I would not advice you to use it.

This should work:

window.test_a = "<?php echo $a ?>";
//.....
console.log ( window[ "test_" + fieldData[0] ] );

To avoid cluttering the global scope, this would be the recommended way:

var myObject = { test_a: "<?php echo $a ?>" };
//.......
console.log ( myObject[ "test_" + fieldData[0] ] );
Community
  • 1
  • 1
PeterKA
  • 24,158
  • 5
  • 26
  • 48