簡體   English   中英

即使變量在 IF 語句中,ESLint 也會拋出 no-undef

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

我正在使用 React,只要我有未定義的變量,我就無法構建我的應用程序。 我僅在 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  

我怎樣才能避免這種行為?

if語句創建一個詞法作用域。 事實上,任何時候您在 javascript 中看到{}都會創建一個范圍。 這意味着在該范圍內使用letconst聲明的變量不能在該范圍之外訪問。

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

您要做的是在要訪問它的范圍內聲明變量,然后在if語句中分配給該變量:

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

請注意,我必須將變量聲明從const更改為let因為我們需要在創建后為其賦值,因此它不能再是常量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM