Javascript While 循环条件与无条件分配错误

olo*_*olo 5 javascript eslint

错误:需要一个条件表达式,但看到一个赋值。( no-cond-assign)

const re = /<%([^%>]+)?%>/g;
let match;
while (match = re.exec('<%hello%> you <%!%>')) {
  console.log(match);
}
Run Code Online (Sandbox Code Playgroud)

执行while循环来重新分配匹配项,但出现no-cond-assign错误。我仍然可以获得没有错误的输出,但是纠正语法的最佳方法是什么?谢谢

Cer*_*nce 4

一种选择是使用do-while循环,这样您就可以breakwhile(true)

const re = /<%([^%>]+)?%>/g;
while (true) {
  const match = re.exec('<%hello%> you <%!%>');
  if (!match) {
    break;
  }
  console.log(match);
}
Run Code Online (Sandbox Code Playgroud)

IMO,这种情况是Javascript 中的一次,其中条件内的赋值(在原始代码中)比替代方案更清晰。我不会害怕禁用这一行的 linting 规则。

假设您想要检索第一个捕获组,您将能够在现代环境中使用string.prototype.matchAll :

const str = '<%hello%> you <%!%>';
const contentInsidePercents = [...str.matchAll(/<%([^%>]+)?%>/g)]
  .map(match => match[1]);
console.log(contentInsidePercents);
Run Code Online (Sandbox Code Playgroud)