2016-09-18 15 views
0

私はJavaScriptを学ぶ過程にあり、私はこのコードで何が間違っているのか悩んでいます。私はこれを行うための簡単な方法があることを知っている '交換'を使用して、私はそれを学習の経験としてまず難しい方法をしようとしています。ループは無限に繰り返されていますが、なぜその理由がわかりません。スクリプトをそのまま実行しようとしないでください。ブラウザがクラッシュします。 :)あなたforループの代わりにテキストの置換ループが機能しない

var text = document.getElementById("docText").innerHTML; 
 
var textFirstChar = text.indexOf("James"); 
 
\t 
 
function nameReplace() { 
 
\t for (var i = 0; i < text.length; i++) { 
 
\t \t if (textFirstChar !== -1) { 
 
\t \t \t text = text.slice(0, textFirstChar) + 
 
\t \t \t "Albert" + text.slice(textFirstChar + 5); 
 
\t \t } 
 
\t } 
 
}
<div id="docText"> 
 
\t <p>Once upon a time there was an angry horse called James the 3rd. James found it difficult to get along with other horses, mainly due to his obnoxious behaviour and wild drinking binges that could go on for days on end, usually only ending when there was no more booze left to steal from his housemates.</p> 
 
    <p>Once day, James got into a fight and was beaten to death, everyone lived happily ever after.</p> 
 
    
 
</div> 
 
<div id="button1"> 
 
<button onclick="nameReplace()">Replace James with Albert</button> 
 
</div>

答えて

2

あなたはwhile (textFirstChar !== -1)を行うと、内部の同じ交換手順を繰り返す必要があります。また、ループ内でtextFirstChar = text.indexOf("James");を実行することを忘れないでください。置換後に、 "James"を検索し続けます。心配しますが、これは非常に非効率です。

+0

ありがとうございます、私は明らかなものが欠けていることを知っていました。私はまた、今行っているテキストを実際に置き換えるための声明を出していませんでした。どうもありがとう! :) – Cuckoo

+0

いいえ問題は、うれしい私が助けることができる:) –

関連する問題