Ral*_*thy 13 javascript string variables type-conversion document.write
是否可以打印/显示JavaScript变量的名称?例如:
var foo=5;
var bar=6;
var foobar=foo+bar;
document.write(foo+ "<br>");
document.write(bar+ "<br>");
document.write(foobar + "<br>");
Run Code Online (Sandbox Code Playgroud)
我们如何打印变量的名称,以便输出:
foo
bar
foobar
Run Code Online (Sandbox Code Playgroud)
而不是:
5
6
11
Run Code Online (Sandbox Code Playgroud)
您可以将变量放在对象中,然后以这种方式轻松打印:http://jsfiddle.net/5MVde/7/
看到小提琴的一切,这是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();
Run Code Online (Sandbox Code Playgroud)
JavaScript for ... in语句循环遍历对象的属性.
另一种变化(感谢@elclanrs),如果你不想foobar成为一个函数:http://jsfiddle.net/fQ5hE/2/
| 归档时间: |
|
| 查看次数: |
27752 次 |
| 最近记录: |