0

I have a few variables set up like this:

var foo, bar, fizz, buzz, hello, world;

Now I want to find out how to get those names as a collection of some sort. I am trying to get them since I want to push them in an array as a string.

I hope it doesnt require eval or something hacky. Is what I am trying to do possible?

I just need to know how to get the names, I prefer to solve the rest myself.

Edit: About the answer from the linked duplicate, I dont really get what he is doing there as I get everything other than names. Ive read it before.

Asperger
  • 3,064
  • 8
  • 52
  • 100
  • 3
    Possible duplicate of [Getting All Variables In Scope](http://stackoverflow.com/questions/2051678/getting-all-variables-in-scope) – Cymen Mar 04 '16 at 08:07
  • 1
    It sounds like you're trying to use a bad solution to solve your problem. What do you want to achieve with these variable names? – Volune Mar 04 '16 at 09:16
  • Sounds like a typical [XY Problem](http://mywiki.wooledge.org/XyProblem) – sabithpocker Mar 04 '16 at 10:41
  • @sabithpocker you are right. Thank you for making me aware of this – Asperger Mar 07 '16 at 08:46

2 Answers2

0

In my opinion it would be better if you have used javascript object here and put variables in it as properties:

var obj = {foo:'', bar:'', fizz:''};

This way you can access both name of the property and its value:

obj.foo
for(key in obj) {
  alert(key + ': ' + obj[key]);
}
Goran
  • 3,292
  • 2
  • 29
  • 32
0

You can get list of variables by Object.keys() method, but it returns all variables that object has:

var ar = Object.keys(this);
console.log(ar);
Slava N.
  • 596
  • 4
  • 6