简体   繁体   English

即使变量在 IF 语句中,ESLint 也会抛出 no-undef

[英]ESLint throws no-undef even if variable is in IF statement

I am using React and I am not able to build my application as long as I have undefined variable.我正在使用 React,只要我有未定义的变量,我就无法构建我的应用程序。 I am using that variable only in IF statement (if it's defined, use it).我仅在 IF 语句中使用该变量(如果已定义,则使用它)。

if (something)
   const newItem = 'wow!';

if (typeof newItem === "undefined")
    console.log('newItem undefined')   
else
    console.log(newItem); //ESLint: Line YY:XX: 'newItem' is not defined  no-undef  

How can I avoid this behavior?我怎样才能避免这种行为?

An if statement creates a lexical scope. if语句创建一个词法作用域。 In fact, any time you see {} in javascript, that creates a scope.事实上,任何时候您在 javascript 中看到{}都会创建一个范围。 What that means is that variables declared with let or const in that scope cannot be accessed outside of that scope.这意味着在该范围内使用letconst声明的变量不能在该范围之外访问。

if (something) {
   const newItem = 'wow!';
   // newItem exists here
}
// newItem does not exist here

What you want to do is declare the variable in the scope where you want to access it, and then just assign to that variable in your if statement:您要做的是在要访问它的范围内声明变量,然后在if语句中分配给该变量:

let newItem;
if (something) {
    newItem = 'wow!';
}
// newItem exists here, and has a value of either 'wow!' or undefined.

Note that I had to change the variable declaration from const to let because we need to assign a value to the value after its creation, so it can no longer be a constant.请注意,我必须将变量声明从const更改为let因为我们需要在创建后为其赋值,因此它不能再是常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM