使用Regex vs include()方法与Switch语句

Using Regex vs includes() method with Switch Statment

本文关键字:方法 Switch 语句 Regex vs include 使用      更新时间:2023-09-26

向OpenWeatherMap.org API发出AJAX请求以获取本地天气预报(温度、城市和天气描述)。我将天气描述分配给变量"weatherDescription"。我正在使用一个开关语句来检查"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");
}

是否有可能完成相同的结果,我收到使用。includes()方法与regEx或有更好的方式来实现这一目标?

问题是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>