为什么要使用“var”里面的循环? [英] why to use "var" inside for in loop?
本文介绍了为什么要使用“var”里面的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,如果我有以下对象:
var a = {
foo:FOO,
bar:BAR
}
现在,如果我想列出这个对象的属性,我应该这样做:
$ ($ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ >
或者,我可以这样做:
for(b in a){
//做某事
}
但,这是这些方法之间的区别吗?为什么要使用var或者为什么不在循环中使用var?
解决方案
使用一个前面没有声明的变量,而不用预先添加 var
,你创建一个全局变量。
function scope(){
a =hi; // global
var b =ho; //本地
}
(
$) code>
和
var b ;
for(b in a){/ * .. * /}
This seems to be easy question, but I can't find an answer for this..
For example if I have the following object:
var a = {
foo : "FOO",
bar : "BAR"
}
Now, if I want to list properties of the objec, I should do the following :
for( var b in a ) {
// do something
}
or, I can do this :
for( b in a ) {
// do something
}
But, which is the difference beetween these methods? Why to use "var" or why not to use "var" in for in loop?
解决方案
If you use a variable that has not been declared before without prepending var
, you create a global variable.
function scope() {
a = "hi"; // global
var b = "ho"; // local
}
However, there is no difference between
for (var b in a) { /* .. */ }
and
var b;
for (b in a) { /* .. */ }
这篇关于为什么要使用“var”里面的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文