Regex TypeError: Cannot read property '1' of null

Regex TypeError: Cannot read property '1' of null

我的日期选择器正则表达式正在尝试匹配空数组。我如何解决它?如果数组为空,则不确定 clazz 应该等于什么。我在想一个简单的 if (matches[1]) { etc } 但我不确定如果 matches 为 null 该怎么办。 Clazz 在代码中的其他地方使用了两次。我只是将 clazz 设置为 null 还是零?

    var matches = exp.match(IS_REGEXP);
    var clazz = scope.$eval(matches[1]);

编辑:这是他们使用 clazz 的地方

    if (data.lastActivated !== newActivated) {
      if (data.lastActivated) {
        $animate.removeClass(data.lastActivated.element, clazz);
      }
      if (newActivated) {
        $animate.addClass(newActivated.element, clazz);
      }
      data.lastActivated = newActivated;
    }

这里是IS_REGEXP

                        11111111           22222222
  var IS_REGEXP = /^\s*([\s\S]+?)\s+for\s+([\s\S]+?)\s*$/;

双重编辑:

这是整个函数

 function addForExp(exp, scope) {
    var matches = exp.match(IS_REGEXP);

      var clazz = scope.$eval(matches[1]);
    var compareWithExp = matches[2];
    var data = expToData[exp];
    if (!data) {
      var watchFn = function(compareWithVal) {
        var newActivated = null;
        instances.some(function(instance) {
          var thisVal = instance.scope.$eval(onExp);
          if (thisVal === compareWithVal) {
            newActivated = instance;
            return true;
          }
        });
        if (data.lastActivated !== newActivated) {
          if (data.lastActivated) {
            $animate.removeClass(data.lastActivated.element, clazz);
          }
          if (newActivated) {
            $animate.addClass(newActivated.element, clazz);
          }
          data.lastActivated = newActivated;
        }
      };
      expToData[exp] = data = {
        lastActivated: null,
        scope: scope,
        watchFn: watchFn,
        compareWithExp: compareWithExp,
        watcher: scope.$watch(compareWithExp, watchFn)
      };
    }
    data.watchFn(scope.$eval(compareWithExp));
  }

如果您只关心 clazz,将 clazz 设置为 null 或空字符串即可。

var clazz = matches ? scope.$eval(matches[1]) : '';

但是对于compareWithExp,当没有匹配时退出整个逻辑可能会更好:

if ( ! matches ) return;