为什么它被认为是最佳实践?
Why is it considered best practice?
我在网站上看到这段代码 w3schools.com(JavaScript 最佳实践)
// Declare at the beginning
var i;
// Use later
for (i = 0; i < 5; i++) {
我不明白为什么声明这个变量被认为是好的做法。它仅在循环中需要。我为什么要让它成为全球
实际上,这段代码已经过时了。最佳做法是使用let
代替var
(see this question on Whosebug,并在for语句中声明:
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
console.log(i); // undefined variable i
let
定义了块作用域变量。此变量不会 "bubble" 到全局范围,通过不污染全局范围来提高效率。
It is a good coding practice to put all declarations at the top of
each script or function.
This will:
Give cleaner code Provide a single place to look for local variables
Make it easier to avoid unwanted (implied) global variables
Reduce the possibility of unwanted re-declarations
你可以这样做让代码更简洁。
但我建议使用 let
而不是 var
.
我在网站上看到这段代码 w3schools.com(JavaScript 最佳实践)
// Declare at the beginning
var i;
// Use later
for (i = 0; i < 5; i++) {
我不明白为什么声明这个变量被认为是好的做法。它仅在循环中需要。我为什么要让它成为全球
实际上,这段代码已经过时了。最佳做法是使用let
代替var
(see this question on Whosebug,并在for语句中声明:
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
console.log(i); // undefined variable i
let
定义了块作用域变量。此变量不会 "bubble" 到全局范围,通过不污染全局范围来提高效率。
It is a good coding practice to put all declarations at the top of each script or function.
This will:
Give cleaner code Provide a single place to look for local variables Make it easier to avoid unwanted (implied) global variables Reduce the possibility of unwanted re-declarations
你可以这样做让代码更简洁。
但我建议使用 let
而不是 var
.