且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么JSLint不允许使用"var"变量?在for循环中?

更新时间:2023-11-05 23:11:58

我同意黑暗绝对主义者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.