为什么JSLint不允许使用"var"变量?在for循环中? [英] Why does not JSLint allow "var" in a for loop?

查看:121
本文介绍了为什么JSLint不允许使用"var"变量?在for循环中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码或plovr出了点问题.我去了JSLint寻求帮助.但是,JSLint似乎将其视为致命错误,并拒绝检查更多代码:

Something is wrong with my code or with plovr. I went to JSLint to get some help. However, JSLint seems to consider this as a fatal error and refuses to check more of the code:

for (var i = 0; i < data.length; i += 4) {

为什么?我喜欢这样声明"I".

Why? I like this way of declaring "I".

如果您使用Windows,则JSHint似乎不是替代方法.我目前正在尝试The Online Lint.我觉得这个bug很难找到,因此我很乐意为您提供有关良好代码检查器的建议.

JSHint does not seem to be an alternative if you are on Windows. I am trying The Online Lint at the moment. I have a feeling that this bug will be a bit difficult to find so I would be glad for suggestions about good code checkers.

推荐答案

我同意黑暗绝对主义者Niet所说的该工具是基于观点的.反思它强加的所有规则,以及它们在您的特定项目中是否真正有意义.它也不是唯一的JavaScript皮棉"工具.也许 ESLint 或其他这样的工具更适合您的需求.

I agree with Niet the Dark Absol that the tool is opinion-based. Reflect on all the rules it imposes and whether they actually make sense in your specific project or not. It's also not the only "lint" tool for JavaScript. Maybe ESLint or another such tool is more suited to your needs.

但是我也不同意他的观点:在函数的开始处声明所有变量不是一个好习惯,尤其是在函数长度较长的情况下,尤其如此,因为这会使您理解程序更难.恕我直言,无论JavaScript的作用域如何工作,它都适用:这与程序语义无关,而与代码的可读性有关!

But I also disagree with him: It is not good practice to declare all your variables at the start of your function, especially not if the function is rather long, since this makes comprehension of your program much harder. IMHO this holds regardless of how the scoping of JavaScript works: It's not about program semantics, it's about code readability!

我认为应该声明一个变量,使其尽可能接近其首次使用(即在您的情况下:在for循环中).这样可以确保阅读您的代码的人(三个月后才是您的同事或您本人)在自己的脑海中所掌握的信息也尽可能少.在开始时声明所有变量将迫使读者在整个函数中牢记所有这些变量.诸如此变量的当前值是多少?"之类的问题或其目的是什么?"变得难以回答.

I would argue that a variable should be declared as close to its first use as possible (i.e. in your case: in the for loop). This ensures that someone reading your code (a colleague or yourself three months from now) has too keep as little information in their head as possible. Declaring all your variables at the start forces the reader to keep all those variables in mind throughout the entire function. Questions like "what's the current value of this variable?" or "what is its purpose?" become harder to answer.

此外,您更容易出于多个目的重用变量.这不仅令人困惑,而且很危险!值可能从第一次使用到第二次泄漏".这可能会导致难以调试的细微问题.

Furthermore, you are much more tempted to reuse a variable for more than one purpose. This is not only confusing, but also dangerous! Values might "leak" from the first use to the second. This can lead to subtle, hard-to-debug problems.

这篇关于为什么JSLint不允许使用"var"变量?在for循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆