打印/显示 JavaScript 变量的名称而不是它的值 [英] Print / display a JavaScript variable's name instead of it's value

查看:32
本文介绍了打印/显示 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/

这篇关于打印/显示 JavaScript 变量的名称而不是它的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆