Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a variable addressable by name as string in JavaScript?

Tags:

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 at some point as I go through the array, I need to get variable names (instead of their values) as strings - that would be 'a' or 'b' or 'c'. And I really need it to be a string so it is writeable. How can I do that?

like image 371
jirkap Avatar asked Jan 06 '09 18:01

jirkap


People also ask

How do you make a string variable in JavaScript?

To declare variables in JavaScript, you need to use the var, let, or const keyword. Whether it is a string or a number, use the var, let, or const keyword for its declaration. But for declaring a string variable we had to put the string inside double quotes or single quotes.

How do you name a variable in JavaScript?

Naming variablesStart them with a letter, underscore _, or dollar sign $. After the first letter, you can use numbers, as well as letters, underscores, or dollar signs. Don't use any of JavaScript's reserved keywords.


2 Answers

Use a Javascript object literal:

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

You can then traverse it like this:

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

And access properties on the object like this:

console.log(obj.a, obj.c); 
like image 120
Kenan Banks Avatar answered Sep 22 '22 17:09

Kenan Banks


What you could 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. } 
like image 27
Paolo Bergantino Avatar answered Sep 23 '22 17:09

Paolo Bergantino