javascript - 文本替换循环不起作用

标签 javascript for-loop

我正在学习 javascript,但我对这段代码做错了什么感到困惑。我知道使用“替换”有更简单的方法来做到这一点,但作为学习经验,我首先尝试以困难的方式做到这一点。循环无限重复,我不知道为什么。请不要尝试按原样运行脚本,它会使您的浏览器崩溃。 :)

var text = document.getElementById("docText").innerHTML;
var textFirstChar = text.indexOf("James");
	
function nameReplace() {
	for (var i = 0; i < text.length; i++) {
		if (textFirstChar !== -1) {
			text = text.slice(0, textFirstChar) +
			"Albert" + text.slice(textFirstChar + 5);
		}
	}
}
<div id="docText">
	<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>

最佳答案

而不是你的for循环你应该做while (textFirstChar !== -1)并在里面重复相同的更换步骤。也不要忘记做textFirstChar = text.indexOf("James");在循环内,替换后,它会继续搜索“James”。请注意,这是非常低效的。

关于javascript - 文本替换循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39557439/

相关文章:

javascript - 关闭 Google Maps MouseWheel Zoom Ctrl

javascript - b.delegate 不是函数异常

javascript - 将 forEach() 方法更改为 For 循环以与 IntersectionObserver 一起使用 - Javascript

python - 用逗号分隔值

c - 为什么我的带有 scanf 的 for 循环没有被执行?

javascript - 为什么 Backbone.View 对象仍然保留在内存中?

Javascript(当浏览器窗口超过 436px 时调整大小)

scala - 具有多个生成器的 for 循环如何在 Scala 中工作?

javascript - Highcharts - setExtremes 后丢失数据

java - 如何在java中打印反向数字图案三角形