javascript - 优化 - 用于语句和变量声明

标签 javascript loops scope

这是报价from MDN关于“for”声明:

An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.

所以当我写这种代码时:

for(var i = 0; i < 10; i++) {
    for(var j = 0; j < 10; j++) {
        // ...
    }
}

在外循环的每次迭代中,我都声明变量 j,它已经被声明为正确的?

那么这样写是不是更好:

for(var i = 0, j = 0; i < 10; i++) {
    for(j = 0; j < 10; j++) {
        // ...
    }
}

...或者我们不在乎?

最佳答案

这句话所指的行为称为提升,在 JavaScript 中了解这一点很重要。

这是如何the MDN explains it :

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

您没有在函数顶部声明所有变量的原因是它们的本地化使代码更清晰。

在第一个循环中声明两个变量绝对没有好处。这只是令人困惑。对于 JS 引擎也是一样,但是其他开发者阅读这段代码会疑惑为什么 j 声明在一个意想不到的位置。

现在,如果您对您的变量在您使用它的循环之前(具有 undefined 值)和之后存在这一事实感到不安,请庆幸:ES6 附带了一个新的声明类型: let,它将变量的范围限定为 block 。

for(let i = 0; i < 10; i++) {
    for(let j = 0; j < 10; j++) {
        // ...
    }
}

Beware: compatibility of let

现在,请使用每个人都期望的标准格式:

for(var i = 0; i < 10; i++) {
    for(var j = 0; j < 10; j++) {
        // ...
    }
}

约定,在这种情况下,ij 不会在 他们的循环。当(并且仅在这种情况下)你想在之后使用 ij 时(例如循环中有一个中断),使用这个:

var i, j;
for(i = 0; i < 10; i++) {
    for(j = 0; j < 10; j++) {
        // ...
    }
}
// use i and j here

关于javascript - 优化 - 用于语句和变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30621035/

相关文章:

javascript - 如何克隆 Vuex 数组?

javascript - 如何使用 Access-Control-Allow-Origin : https://www. example.com?

arrays - 在 Swift 中删除 UIButtons 数组

javascript - 尝试构建一个 javascript 库,但未能完成简单的启动它

html - 清除和重置 Web 表单有什么区别?

javascript - Angular 2.0 ngClass 未在超时时更新

string - 批量 - 获取当前运行系统的系统语言

php - 如何使用数组函数合并 php 中的内部数组元素?

javascript - 将类添加到 AngularJs 中的多个元素

javascript - 为什么我无法在这个简单的函数中访问这个变量?