簡體   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