【问题标题】:no-unused-vars error despite while loop using variable尽管 while 循环使用变量,但没有未使用的变量错误
【发布时间】:2020-04-08 10:21:03
【问题描述】:

在这个例子中,一个函数声明了一个变量,inComingColor,然后这个变量在随后的 while 循环中使用。

priority(to: Position, cols: Color[][]) {
    let index = to.index + 1; 
    let colorMatchCount = 0;
    let inComingColor = cols[to.col][to.index]; // no-unused-vars error

    while(index < 4) {
        if(inComingColor = cols[to.col][index]) {    // variable used here
            colorMatchCount++;
            index++;
        } else return 0;
    }
    return colorMatchCount;
}

但是,在这个变量的实例化旁边会出现一个 tslint 错误:

'inComingColor' 被赋值但从未使用过
@typescript-eslint/no-unused-vars

我的猜测是 linter 提出这个投诉是因为可能会出现大于 3 的索引。然后 while 循环将永远不会执行,inComingColor 将永远不会被使用。 (这实际上不会发生,因为这些 Color[] 类型的长度上限为 4)。

不管怎样,不必禁用内联错误,有没有一种简洁的方法来重构这个函数,使错误消失?

编辑:看起来 linter 只是发出了一个无用的错误。我有一个错误。 if 语句不应该使用赋值运算符:

if(inComingColor === cols[to.col][index]) {   // correct: error disappears

【问题讨论】:

  • 不,您实际上从未使用过它。 if 语句只关心表达式的结果,这只是您分配给变量的值 (cols[to.col][index])。您将其分配给变量的事实与 if 语句无关,因为您以后再也不会对它做任何事情,毫无意义。

标签: typescript tslint


【解决方案1】:

您需要在 if 检查之前分配它:

        inComingColor = cols[to.col][index];
        if(inComingColor) {    // variable used here

或者只是检查您分配给它的值:

        if(cols[to.col][index]) {

【讨论】:

  • 这将在声明变量的行中导致“未使用值”警告,该变量会为inComingColor 分配一个值,该值在用于任何操作之前肯定会被覆盖。根据 OP 的编辑,if 语句中的赋值应该是 ===== 比较。
猜你喜欢
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 2018-06-10
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
相关资源
最近更新 更多