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

时间:2017-02-08 13:04:41

标签: 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;
}

鉴于上面的伪代码,我从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

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

3 个答案:

答案 0 :(得分:5)

const是块范围的。所以你在那里做的是在执行的任何块中创建a,不使用它,让它超出范围,然后尝试返回不同的 {{1}函数关闭(如果没有a被关闭,将导致ReferenceErrora行不引用其上方任何一个块中声明的return a;;那个人已经超出了范围。

所以相反:

a

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

答案 1 :(得分:1)

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

你需要像

那样定义它
stdClass Object
(
    [success] => 1
    [message] => Array
        (
            [code] => 000
            [txt] => Operation successful
        )

    [data] => Array
        (
            [result] => OK
            [accountID] => 000000000
            [group] => demoCAC
            [currency] => USD
            [enable] => 1
            [read_only] => 0
            [name] => Bogus Demo
            [country] => ****
            [city] => 
            [address] => 
            [phone] => **
            [email] => ***@gmail.com
            [status] => test
            [regdate] => 07/02/2017 09:57
            [lastdate] => 07/02/2017 09:57
            [balance] => 0.00
            [credit] => 0.00
            [equity] => 10000.00
            [isDemo] => 1
            [tp_version] => **
            [last_name] => Demo
            [first_name] => Bogus
            [domain] => ***.com
            [compliance] => 
            [latestTrades] => Array
                (
                    [results] => Array
                        (
                        )

                    [totalResults] => 0
                )

            [owner] => 
        )
    )

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

答案 2 :(得分:0)

常量是块作用域的,就像使用let语句定义的变量一样。常量的值不能通过重新赋值来改变,也不能重新声明。

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