【问题标题】:ESLint no-unused-vars and no-undef error but variable is usedESLint no-unused-vars 和 no-undef 错误但使用了变量
【发布时间】:2017-06-26 02:54:20
【问题描述】:

我正在使用 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

关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: javascript ecmascript-6 eslint


    【解决方案1】:

    const 是块范围的。所以你在那里做的是在执行的任何块中创建一个a,而不是使用它,让它超出范围,然后尝试返回一个 不同 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 中的a 与 else 中的那个无关;它们是不同的,因为变量被重新创建并且未被使用。
    • @AndrewLi:是的,你可能是对的。我开始使用的那句话的版本(从未发布过,我先更改了它)做出了区分,但不清楚。 :-)
    【解决方案2】:

    你在 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

    【讨论】:

      【解决方案3】:

      常量是块范围的,很像使用 let 语句定义的变量。常量的值不能通过重新赋值改变,也不能重新声明。

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

      【讨论】:

        猜你喜欢
        • 2019-07-06
        • 2018-06-27
        • 1970-01-01
        • 2020-01-25
        • 2019-01-12
        • 2020-03-01
        • 2020-11-26
        • 1970-01-01
        相关资源
        最近更新 更多