gpt4 book ai didi

javascript - Jslint 提示数组迭代

转载 作者:行者123 更新时间:2023-11-28 00:58:43 24 4
gpt4 key购买 nike

为什么 jslint 会提示这个?

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

错误信息是:

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

对于我来说,在比必要范围更广的范围内声明变量是没有意义的(顺便说一句,for block 是否有各自的sope?)。

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

最佳答案

Javascript 没有 block 作用域,因此:

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讨论这种方法的优点和缺点。

关于javascript - Jslint 提示数组迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25913916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com