ESLint no-unused-vars 和 no-undef 错误但使用了变量

ESLint no-unused-vars and no-undef error but variable is used

我正在使用 ESLint 检查构建时的 javascript 代码,我收到一个 no-unused-vars 错误,然后是同一变量的 no-undef 错误。我无法理解变量如何既未使用又未定义。

export function count(){
    if (counter > 3){
        const a = 'big';
    } else {
        const a = 'small';
    }
    return a;
}

鉴于上面的伪代码表示,我从 ESLint 得到以下错误:

line 3 error  'a' is defined but never used  no-unused-vars
line 5 error  'a' is defined but never used  no-unused-vars
line 7 error  'a' is not defined             no-undef

关于如何解决这个问题有什么想法吗?

const 是 block-scoped。所以你在那里做的是在执行的任何块中创建一个 a,不使用它,让它超出范围,然后尝试 return 一个 不同的 a 函数关闭(如果没有 a 被关闭,这将导致 ReferenceError)。 return a; 行不引用在它上面的任何一个块中声明的 a ;到那时那个已经超出范围了。

所以改为:

export function count(){
    const a = counter > 3 ? 'big' : 'small';
    return a;
}

export function count(){
    let a; // Declared outside the blocks
    if (counter > 3){
        a = 'big';
    } else {
        a = 'small';
    }
    return a;
}

你在 if 中定义你的 const,它不在函数范围内。

你需要这样定义

 export function count(){
    let a;
    if (counter > 3){
        a = 'big';
    } else {
        a = 'small';
    }
    return a;
}

更多信息,阅读下一章节 https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures

常量是 block-scoped,很像使用 let 语句定义的变量。常量的值不能通过re-assignment改变,也不能重新声明。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const