[英]Comma after variable assignment in Javascript
function ReplaceContentInContainer(matchClass,content)
{
var elems = document.getElementsByTagName('*'), i;
for (i in elems)
{
if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1)
{
elems[i].innerHTML = content;
}
}
}
I'm trying to figure out what the comma does in the variable assignment ('*'), i;
我试图弄清楚逗号在变量赋值中的作用('*'), i;
and what that means in the for (i in e)
loop. 以及for (i in e)
循环中的含义。
My best guess is that e
is assigned to both all the elements in the document node as well as i
. 我最好的猜测是, e
被分配给文档节点中的所有元素以及i
。 So does that mean that i
is a count or reference of the number of elements in the array e
(is it an array?)? 那么这是否意味着i
是数组e
中元素数量的计数或引用(它是一个数组?)?
edit: Okay. 编辑:好的。 It's just instantiating the variable ( i
) and then i
, in the for
loop, counts all the elements in the object elem
. 它只是实例化变量( i
)然后i
,在for
循环中,计算对象elem
中的所有元素。
That simply separate the declarations. 这只是简单地分隔声明。
var elems = document.getElementsByTagName('*'), i;
is the same as 是相同的
var elems = document.getElementsByTagName('*');
var i;
One is more concise, the other one might be seen as more readable. 一个更简洁,另一个可能被认为更具可读性。
In your precise case, you could have used 在您的确切情况下,您可以使用
var elems = document.getElementsByTagName('*');
for (var i in elems)
which would be, in my opinion, the best as the purpose of i
would have been obvious. 这将是,在我看来,最好为目的i
本来是显而易见的。
As the scope of a variable is the function (or global) and not the block, it would have been exactly identical. 由于变量的范围是函数(或全局)而不是块,因此它将完全相同。
That comma is because you define the variable i
in the local scope, it's simply part of the var
statement. 这个逗号是因为你在本地范围内定义变量i
,它只是var
语句的一部分。 If there wasn't a comma i
would be a global. 如果没有逗号, i
将是一个全球性的。
Your statement is the same as: 您的陈述与以下内容相同:
var elems = document.getElementsByTagName('*');
var i;
If you use tool for static analysis of the quality of your code, like JSLint for example, it'll force you to write: 如果您使用工具进行代码质量的静态分析,例如JSLint,它会强制您编写:
var elems = document.getElementsByTagName('*'),
i;
In few reasons: 原因如下:
var
(you write less... :-)) 你没有额外的var
(你写得少...... :-)) You define all your variables at the same place which is easier for reading than: 您可以在同一个地方定义所有变量,这些变量比以下内容更容易:
for (var i in elems) { //do something } for(var i in elems){// do something}
There's similar concept in perl, for example: perl中有类似的概念,例如:
my ($var1, $var2);
In JavaScript it's the same but you don't need to put the variables inside a list. 在JavaScript中它是相同的,但您不需要将变量放在列表中。
i
is the part of the var
statement.. so it is just creating a new variable... you code is same as i
是var
语句的一部分..所以它只是创建一个新的变量...你的代码是相同的
var elements=document.getElementsByTagName('*');
var i;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.