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

Don*_*the 3 javascript ecmascript-6 eslint

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

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

鉴于上面的伪代码,我从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
Run Code Online (Sandbox Code Playgroud)

有关如何绕过这个的任何想法?

T.J*_*der 5

const是块范围的.所以你在那里做的是创建一个a内部任何一个块执行,不使用它,让它超出范围,然后尝试返回一个不同 a的功能关闭(ReferenceError如果没有a关闭将导致过度).该return a;行未引用其a上方任何一个块中声明的行; 那个人已经超出了范围.

所以与其:

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

要么

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