xra*_*alf 41 javascript variables declaration
在本教程中有写:
If you redeclare a JavaScript variable, it will not lose its value.
我为什么要重新声明变量?在某些情况下它是否实用?
谢谢
Tha*_*Guy 52
这只不过是一个提醒,如果你这样做:
var x=5;
var x;
alert(x);
Run Code Online (Sandbox Code Playgroud)
结果将是5.
例如,如果您在某些其他语言中重新声明变量 - 结果将是未定义的,或NaN,但不是在javascript中.
小智 38
可以在Google Analytics中找到重新声明变量的示例.当JavaScript跟踪代码由Google Analytics脚本启动时,它会_gaq以这种方式声明或重新声明:
var _gaq = _gaq || [];
Run Code Online (Sandbox Code Playgroud)
换句话说,如果_gaq已经定义,_gaq则"重新声明"为其自身.如果没有定义,它将首次声明为空数组.
这样,Google Analytics跟踪代码就可以支持在Google Analytics代码启动之前可能需要使用该变量的其他脚本.正如@xralf所指出的,JavaScript允许这样做.
在无法知道变量是否已被定义的情况下,重新声明变量非常有用.
通过有条件地重新声明变量,就像Google Analytics跟踪代码一样,它允许变量安全地来自多个地方.
在此示例中,使用_gaq变量的其他代码同样检查预定义_gaq变量可能是安全的.如果它存在,它知道它可以使用它.如果它不存在,它知道它应该在尝试使用它之前定义它.
Que*_*tin 20
我为什么要重新声明变量?
你不应该.这会使代码混乱.
在某些情况下它是否实用?
没有.
在javascript中没有块范围,因此建议重新声明变量以用于澄清目的; 这样可以获得更好的代码.
例如:
for (var x=0; x< 100; x++) { }
alert(x); //In most languages, x would be out of scope here.
//In javascript, x is still in scope.
//redeclaring a variable helps with clarification:
var x = "hello";
alert(x);
Run Code Online (Sandbox Code Playgroud)
它不会因为吊装而失去其价值
var x = 5;
var x;
// this is same as
var x; // undefined;
x = 5;
Run Code Online (Sandbox Code Playgroud)
因此,当您说“如果您重新声明 JavaScript 变量,它不会丢失其值”。
根据提升,所有声明都会移至顶部。然后给变量赋值。
var x = 25;
var x; // redeclare first time
var x; // redeclare second time
// is same as
var x; // undefined
var x; // Not sure if this happens, but doesn't make a difference, it's still undefined
x = 25;
Run Code Online (Sandbox Code Playgroud)
至于实用性,有时会发生这种情况。看看@steveoliver 的回答。