Jslint抱怨迭代数组

时间:2014-09-18 13:23:04

标签: javascript jslint

为什么jslint抱怨这个?

for (var i = 0; i < array.length; i ++) {
    console.log(array[i]);
}

错误消息是:

Move 'var' declarations to the top of the function.

对于我来说,在更广泛的范围内声明变量比没有必要(块的每个都有自己的btw?)。

这里有什么问题?如果这只是jslint的一时兴起,是否有可能让它以某种方式忽略这个特定情况呢?

1 个答案:

答案 0 :(得分:1)

Javascript没有块范围,所以:

function foo() {

   // some code

   for (var i = 0; i < a.length etc

与:

相同
function foo() {

   var i;

   // some code

   for (i = 0; i < a.length etc

JSLint认为您可能不了解JS范围规则,并建议您根据解释器的实际工作方式重构源代码 - 即使用第二个选项。

我个人从不这样做,因为上下文声明严重降低了可读性:

function foo() {

   var i; // what the heck is this for?

   // some code
   // more code
   // even more code

   for (i = 0; i < a.length // where the heck does this come from?

http://c2.com/cgi/wiki?DeclareVariablesAtFirstUse讨论了这种方法的优缺点。