[英]How do I get the code after the for-loop to not run until the for-loop has completed its interations?
[英]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.