no-unused-vars 错误尽管 while 循环使用变量

no-unused-vars error despite while loop using variable

在此示例中,一个函数声明了一个变量,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' is assigned a value but never used
@typescript-eslint/no-unused-vars

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

无论如何,在不必禁用在线错误的情况下,是否有一种简洁的方法来重构此函数以使错误消失?

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

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

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

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

或者只检查您为其分配的值:

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