繁体   English   中英

我怎样才能使这段代码正常工作,它基于一个for循环并且没有完成它的过程

[英]How can i make this code work properly, its based on a for-loop and is not completing its process

for (let i = 0; i < ans.length; i++) {
  ans = ans.replace(' ', '+');
  ans = ans.replace('  ', '+');
  ans = ans.replace('++', '+');
  //here ans is a value of an input.
}

为什么在完成该过程之前停止?

您在循环的每次迭代中都执行相同的操作,因此此代码块中的循环是多余的。 如果您打算替换所有匹配项,则使用正则表达式替换会更好:

ans = ans.replace(/ /g, '+');
ans = ans.replace(/  /g, '+');
ans = ans.replace(/\+\+/g, '+');

如果您只针对现代浏览器,您可以使用replaceAll代替:

ans = ans.replaceAll(' ', '+');
ans = ans.replaceAll('  ', '+');
ans = ans.replaceAll('++', '+');

好吧,根据我看到的代码,无论连续多少个空格,您都想摆脱空格,所以我建议使用正则表达式

let ans = "im an input here   so you can see the stuff"
ans = ans.replace(/\s+/g , '+'); \* im+an+input+here+so+you+can+see+the+stuff *\

正如在Wais Kamal Answer上所说的那样,您也可以将replaceAll()用于不同的情况

为什么在完成该过程之前停止?

要回答您唯一的问题,循环过早结束,因为您写入ans变量并因此更改ans的长度(用作for循环中的条件)。 所以如果你缩短长度,它会更早停止。

但是请查看其他人的答案以了解如何更好地编写它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM