打字稿阴影变量

RBa*_*iak 4 typescript

我在TypeScript项目中使用TSLint,它i在以下代码中抱怨变量:

    for (let i = 0; i < body.children.length; i++)
    {
        body.children[i].classList.remove('active');
    }
Run Code Online (Sandbox Code Playgroud)

信息是 'Shadowed variable: 'i' (no-shadowed-variable)'

这个循环有什么问题吗?在TS中执行for循环的正确方法是什么?

Obl*_*sys 14

阴影意味着声明已在外部作用域中声明的标识符.由于这是一个linter错误,它本身并不是错误的,但它可能会导致混淆,以及使i循环中的外部不可用(它被循环变量遮蔽).

您可以重命名任一i变量,但如果您将规则添加"prefer-for-of": true到您的tslint.json,则TSLint将在这种情况下建议一个优雅的解决方案:

for (const child of body.children) {
    child.classList.remove('active');
}
Run Code Online (Sandbox Code Playgroud)

(child已提供尚未宣布:-)