首先,如果之前有人问过这个问题,我深表歉意。我已经搜索过与我在这里要问的类似的东西,但除了死胡同什么也没找到。
我正在审查一个项目的一些旧代码,我使用 Brackets 作为我的 IDE 和 JSLint 扩展。在检查我的代码时,它建议我更改类似于
的行for(var i = 0; i < somevalue; i++)
到
var i;
for(i = 0; i < somevalue; i++)
这促使我问;从性能方面、编码标准方面等方面来看,这两个声明之间是否存在显着差异?
感谢您提供任何答案或线索!
最佳答案
JSLint 是 actually asking you to move the variable declaration to the top of the function scope :
function myfunction() {
var i,
j,
k;
// other code
for (i = 0; i < 100; i=i+1) { //another JSLint Recommendation: Don't use ++
for (j = 0; j < 100; j=j+1) {
for (k = 0; k < 100; k=k+1) {
console.log(i);
console.log(j);
console.log(k);
}
}
}
}
原因是变量在 JavaScript 中具有函数级作用域。如果我在 for
循环内为 i
声明了 'j',it would have been 'hoisted' to the top of the function并且实际上会存在于整个函数中,而不仅仅是 for
循环中。
JSLint 提出此建议是因为无论如何这就是幕后发生的事情,如果您不希望出现这种情况,您可能会感到意外。
关于javascript - var i = somevalue; 之间有什么区别?和变种我;我=一些值(value);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28112171/