打印/显示JavaScript变量的名称而不是它的值 [英] Print / display a JavaScript variable's name instead of it's value
问题描述
是否可以打印/显示JavaScript变量的名称?例如:
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
而不是:
5
6
11
推荐答案
您可以将变量放在 对象 然后以这种方式轻松打印出来: http://jsfiddle.net/5MVde/7/
You can put the variables in an object then easily print them this way: http://jsfiddle.net/5MVde/7/
查看小提琴对于一切,这是JavaScript ......
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();
JavaScript for ... in 语句循环遍历 对象 。
The JavaScript for...in statement loops through the properties of an object.
另一种变体(感谢@elclanrs),如果你不想要 foobar
成为一个功能: http:// jsfiddle .net / fQ5hE / 2 /
Another variation (thanks @elclanrs) if you don't want foobar
to be a function: http://jsfiddle.net/fQ5hE/2/
这篇关于打印/显示JavaScript变量的名称而不是它的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!