typescript 打字稿阴影变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46393505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript shadowed variable
提问by RBasniak
I'm using TSLint in a TypeScript project and it's complaining about the variable i
in the following code:
我在 TypeScript 项目中使用 TSLint,它抱怨i
以下代码中的变量:
for (let i = 0; i < body.children.length; i++)
{
body.children[i].classList.remove('active');
}
The message is 'Shadowed variable: 'i' (no-shadowed-variable)'
消息是 'Shadowed variable: 'i' (no-shadowed-variable)'
Is there anything wrong with this loop and what would be the correct way of doing a for loop in TS?
这个循环有什么问题吗?在 TS 中执行 for 循环的正确方法是什么?
回答by Oblosys
Shadowing means declaring an identifier that has already been declared in an outer scope. Since this is a linter error, it's not incorrect per se, but it might lead to confusion, as well as make the outer i
unavailable inside the loop (where it is being shadowed by the loop variable.)
阴影意味着声明一个已经在外部作用域中声明的标识符。由于这是一个 linter 错误,它本身并没有错,但它可能会导致混淆,并使外部i
在循环内不可用(它被循环变量遮蔽)。
You can rename either of the i
variables, but if you add the rule "prefer-for-of": true
to your tslint.json
, TSLint will suggest an elegant solution in this case:
您可以重命名任何一个i
变量,但如果您将规则添加"prefer-for-of": true
到您的tslint.json
,TSLint 将在这种情况下建议一个优雅的解决方案:
for (const child of body.children) {
child.classList.remove('active');
}
(provided child
hasn't been declared already :-)
(前提child
是尚未声明:-)