打印/显示 JavaScript 变量的名称而不是它的值

是否可以打印/显示 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

推荐答案

你可以把变量放在 object 然后以这种方式轻松打印它们:http:///jsfiddle.net/5MVde/7/

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

一切见 fiddle,这是 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.

如果您不希望 foobar 成为函数,则另一种变体(感谢@elclanrs):http://jsfiddle.net/fQ5hE/2/

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

相关文章