错误:需要一个条件表达式,但看到一个赋值。( 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错误。我仍然可以获得没有错误的输出,但是纠正语法的最佳方法是什么?谢谢
一种选择是使用do-while循环,这样您就可以break在while(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)