期望一个条件表达式,而是看到一个赋值

时间:2017-10-23 06:50:47

标签: javascript

我的javascript代码中有以下功能:

  addParam(url, param, value) {
    var a = document.createElement('a'), regex = /(?:\?|&|&)+([^=]+)(?:=([^&]*))*/g;
    var match, str = []; a.href = url; param = encodeURIComponent(param);

    while(match = regex.exec(a.search)) {
      if(param != match[1]) {
        str.push(match[1] + (match[2] ? '=' + match[2] : ''));
      }
    }

    str.push(param + (value ? '=' + encodeURIComponent(value) : ''));
    a.search = str.join('&');
    return a.href;
  }

eslint会在返回错误后返回:

  306:15  error  Expected a conditional expression and instead saw an assignment  no-cond-assign

问题在于声明:

while(match = regex.exec(a.search)) {
  if(param != match[1]) {
    str.push(match[1] + (match[2] ? '=' + match[2] : ''));
  }
}

如何重写此内容以解决此问题?

1 个答案:

答案 0 :(得分:10)

你想这样做:

while((match = regex.exec(a.search))) {
  if(param != match[1]) {
    str.push(match[1] + (match[2] ? '=' + match[2] : ''));
  }
}

你需要额外的一组括号