4

If I have some Javascript code like the following...

(function(){
    var a = 'valueA';
    var b = 'valueB';
    var c = 'valueC';

    //Create a loop that prints the name of all variables created above
    for(var x in ?????){
        console.log(x);
    }
})();

How do I print out a list of the variables that have been declared and assigned inside the anonymous function.

Mike
  • 3,855
  • 5
  • 30
  • 39
  • 1
    possible duplicate of [Programmatically get values of variables local to function in javascript?](http://stackoverflow.com/questions/745495/programmatically-get-values-of-variables-local-to-function-in-javascript) – Ben Lee Dec 01 '11 at 07:43
  • 1
    mike it seems not possible. you can read this link http://stackoverflow.com/questions/275351/javascript-reflection . maybe you should change your variable defination. – erimerturk Dec 01 '11 at 08:04
  • Yes it seems it WAS a duplicate! Thanks for your replies... I had a feeling it might not be possible! – Mike Dec 01 '11 at 08:32

2 Answers2

1

As mentioned above in a comment, it is not possible, as explained in this link Javascript Reflection

Community
  • 1
  • 1
Mike
  • 3,855
  • 5
  • 30
  • 39
-1

This is very easy if the variables are in an array:

function printVariable() {
   var newArray = [valueA, valueB, valueC....];
   var i;

   for (i = 0; i < newArray.length; i++) {
      console.log(newArray(i));
   }
}
  • 1
    Then they aren't variables, they're array members, so this isn't a suitable answer. – RobG Dec 01 '11 at 09:04
  • Sure, but if you create the array from the variables then it is a viable answer. OFC this would require knowledge of how many variables there are. – Kevin Anthony Oppegaard Rose Dec 01 '11 at 09:27
  • How do you propose to `create the array from the variables`? You can't access a function's variable object, so you can't iterate over it. You could use ES5 features to create a *set* method for object properties that reflect their values in local variables, but that would be an awkward solution. – RobG Dec 02 '11 at 00:39
  • The variables come from somewhere. When they are created put them into the array. Use array.push. OFC it gets more complicated if they are initialised in a different function, but then they will need to be parsed to this function and could be pushed to the array at the start. Not the best solution, I admit. But I see no reason why it would not work. – Kevin Anthony Oppegaard Rose Dec 02 '11 at 05:29
  • 3
    So you have an array with some values that have no relationship to the variables other than some order that can be discovered only by looking at the source code. The OP is: `How do I print out a list of the variables that have been declared and assigned inside the anonymous function`. – RobG Dec 02 '11 at 08:26
  • The variables need to either be parsed to the function or created within the function. Either way you can simply add them to an array. – Kevin Anthony Oppegaard Rose Dec 02 '11 at 08:33