Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  113] [ 4]  / answers: 1 / hits: 33011  / 10 Years ago, fri, march 21, 2014, 12:00:00

Is it possible to print / display a JavaScript variable's name? For example:



var foo=5;
var bar=6;
var foobar=foo+bar;

document.write(foo+ <br>);
document.write(bar+ <br>);
document.write(foobar + <br>);


How would we print the variable's names so the output would be:



foo 
bar
foobar


Rather than:



5
6
11

More From » string

 Answers
45

You can put the variables in an object then easily print them this way: http://jsfiddle.net/5MVde/7/



See fiddle for everything, this is the JavaScript...



var x = {
foo: 5,
bar: 6,
foobar: function (){
var that=this;
return that.foo+that.bar
}
};

var myDiv = document.getElementById(results);

myDiv.innerHTML='Variable Names...';
for(var variable in x)
{
//alert(variable);
myDiv.innerHTML+='<br>'+variable;
}

myDiv.innerHTML+='<br><br>And their values...';
myDiv.innerHTML+='<br>'+x.foo+'<br>'+x.bar+'<br>'+x.foobar();


The JavaScript for...in statement loops through the properties of an object.



Another variation (thanks @elclanrs) if you don't want foobar to be a function: http://jsfiddle.net/fQ5hE/2/


[#71875] Wednesday, March 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leslijessalyng

Total Points: 650
Total Questions: 85
Total Answers: 109

Location: Croatia
Member since Mon, Sep 6, 2021
3 Years ago
leslijessalyng questions
Fri, Feb 21, 20, 00:00, 4 Years ago
Tue, Jul 30, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
;