我的代碼中有一個指向字串中某個字符的索引值,我必須用上一個值和下一個值交替替換該字符的所有實體,但給定索引字符的值除外。以下是我實作這一目標的代碼:
function replaceChar(string,idx){
a = string[idx]
b= []
pre_val = string[idx - 1]
post_val = string[idx 1]
for(let i=0; i< string.length; i ){
if(i==idx){
繼續。
}
if (string[i]==a){
b.push(i)
}
}
for(i=0; i<b.length; i ){
if (i%2==0){
string = string.replace( string[b[i]], pre_val)
}
if (i%2==1) {
string = string.replace(string[b[i]], post_val)
}
}
return string
}
給出的輸入是:
console。 log(replaceChar('Baddy'/span>,2)
首選輸出是:
Baday。
我得到的結果是:
Baady
string = string.replace( string[b[i]], pre_val)
=> 上述陳述句中b[i]的值是3,所以string[3]應該被替換成a(之前的值),輸出應該是Baday。不知道哪里出了問題。
uj5u.com熱心網友回復:
因為你想在某個索引處替換一個字符,而且你要做多次替換(潛在的),你可以用一個陣列來代替(暫時的):
let tmp = string.split(''/span>); /from string into array
for(let i = 0; i<b.length; i ){
if (i%2==0){
tmp[b[i]] = pre_val;
}
if (i%2==1){
tmp[b[i]] = post_val。
}
}
return tmp.join('') //back into a string。
此外,你還需要正確宣告你的其他變數。
let a = string[idx] 。
let b = [] 。
let pre_val = string[idx - 1]
let post_val = string[idx 1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324477.html
標籤:
上一篇:如何修復。TypeError:unsupportedoperandtype(s)for/:'str'和'float'。
