Ade*_*emo 27 javascript typescript tslint angular
我有一个函数,它根据传入的特定规则检查顺序流中的当前阶段,并根据该值在我的Angular 2应用程序中分配下一个值.它看起来像这样:
private getNextStageStep(currentDisciplineSelected) {
const nextStageStep = '';
if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 1') {
const nextStageStep = 'step 2';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 2') {
const nextStageStep = 'step 3';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 3') {
const nextStageStep = 'step 4';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 4') {
const nextStageStep = 'step 5';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 5') {
const nextStageStep = 'step 6';
}
return nextStageStep;
}
Run Code Online (Sandbox Code Playgroud)
我在这里做的是返回"nextStageStep"的值,因为这就是我将要传递的内容,以便正确的阶段步骤发生.
现在,我的tslint使用警告"no shadowed variables"强调每个"nextStageStep"变量的出现.如果我删除我初始化为一个警告消失的空字符串的行,但是我得到错误,"找不到nextStageStep"出现在我的return语句中.
原始阴影变量警告有什么问题,是否有另一种方法可以写这个,和/或我应该在这种情况下忽略tslint警告?
tos*_*skv 48
linter抱怨因为你多次重新定义同一个变量.从而替换包含它的封闭物中的那些.
而不是重新声明它只是使用它:
private getNextStageStep(currentDisciplineSelected) {
let nextStageStep = '';
if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 1') {
nextStageStep = 'step 2';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 2') {
nextStageStep = 'step 3';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 3') {
nextStageStep = 'step 4';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 4') {
nextStageStep = 'step 5';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 5') {
nextStageStep = 'step 6';
}
return nextStageStep;
}
Run Code Online (Sandbox Code Playgroud)
一般来说,
当局部作用域中的变量和包含作用域中的变量具有相同的名称时,就会发生遮蔽。隐藏使得无法访问包含范围内的变量,并且模糊了标识符实际引用的值。
const a = 'no shadow';
function print() {
console.log(a);
}
print(); // logs 'no shadow'.
const a = 'no shadow';
function print() {
const a = 'shadow'; // TSLint will complain here.
console.log(a);
}
print(); // logs 'shadow'.
Run Code Online (Sandbox Code Playgroud)
请参阅本文以获取解释这一点的代码示例。
这与在不同范围内定义相同的变量有关。nextStageStep您在函数作用域内以及每个 if 块内进行定义。一种选择是删除 if 块中的变量声明
if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 1') {
nextStageStep = 'step 2';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 2') {
nextStageStep = 'step 3';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 3') {
nextStageStep = 'step 4';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 4') {
nextStageStep = 'step 5';
} else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 5') {
nextStageStep = 'step 6';
}
Run Code Online (Sandbox Code Playgroud)
这是关于阴影变量的好资源http://eslint.org/docs/rules/no-shadow
| 归档时间: |
|
| 查看次数: |
44641 次 |
| 最近记录: |