簡體   English   中英

將Regex vs include()方法與Switch Statment一起使用

[英]Using Regex vs includes() method with Switch Statment

我向OpenWeatherMap.org API發出AJAX請求,以獲取本地天氣預報(溫度,城市和天氣描述)。 我將天氣描述分配給變量“ weatherDescription”。 我正在使用switch語句檢查“ weatherDescription”在說明中是否具有“ clouds”,並且是否確實將DOM中元素的圖像圖標更改為“ cloudy”圖標圖像。

以下代碼可在Chrome中運行,但不幸的是.includes()方法在其他瀏覽器(Safari,IE,Opera等)中無法使用。

function SwitchIcons() {
        switch (true) {
          case (weatherDescription.includes('clear')):
            icon.className = "";
            icon.classList.add("wi", "wi-day-sunny");
            break;
          case (weatherDescription.includes('rain')):
            icon.className = "";
            icon.classList.add("wi", "wi-day-rain");
        }
      }
      SwitchIcons();

因此,我現在正在針對regExp測試“ weatherDescription”,但對於第一種情況(以下示例),條件始終返回true:

var myRegExp = /sun|rain|sleet/ig; 
switch (true) {
              case myRegExp.test(weatherDescription)):
                icon.className = "";
                icon.classList.add("wi", "wi-day-sunny");
                break;
case myRegExp.test(weatherDescription)):
icon.className = "";
icon.classList.add("wi", "wi-day-rain");
}

是否可以使用regEx使用.includes()方法獲得與我收到的結果相同的結果,還是有更好的方法實現這一目標?

問題是g修飾符。 第二次調用test將嘗試從上一個匹配開始匹配 ,而不是從字符串開頭開始匹配。 JavaScript中的正則表達式對象具有狀態,當您將gtestexec一起使用時,狀態很重要。

這是一個更簡單的示例來說明問題:

 var rex; rex = /test/g; snippet.log(rex.test("test")); // true snippet.log(rex.test("test")); // false // vs. rex = /test/; snippet.log(rex.test("test")); // true snippet.log(rex.test("test")); // true 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

暫無
暫無

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

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