How to convert variable name to string in JavaScript?

Is there a way to convert variable names to strings in javascript? To be more specific:

var a = 1, b = 2, c = 'hello'; var array = [a, b, c]; 

Now, when I look at the array, I need to get the names of the variables (instead of their values) as strings - this will be "a" or "b" or "c". And I really need it to be a string, so it can be written. How can i do this?

+22
javascript
Jan 6 '09 at 18:33
source share
3 answers

Use a Javascript object literal:

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

Then you can execute it as follows:

 for (var key in obj){ console.log(key, obj[key]); } 

And object access properties like this:

 console.log(obj.a, obj.c); 
+25
Jan 06 '09 at 18:36
source share
— -

What you can do is something like:

 var hash = {}; hash.a = 1; hash.b = 2; hash.c = 'hello'; for(key in hash) { // key would be 'a' and hash[key] would be 1, and so on. } 
+3
Jan 06 '09 at 18:39
source share

Drop the triptych stuff (thanks) ...

 (function(){ (createSingleton = function(name){ // global this[name] = (function(params){ for(var i in params){ this[i] = params[i]; console.log('params[i]: ' + i + ' = ' + params[i]); } return this; })({key: 'val', name: 'param'}); })('singleton'); console.log(singleton.key); })(); 

Just thought it was a cute little standalone model ... hope this helps! Thanks Triptych!

0
Aug 25 '12 at 9:15
source share



All Articles