我的代码中是否存在无限循环
Is there an infinite loop in my code?
当我运行这个时,我的网页崩溃了:
function replace()
{
var str = document.getElementById('feeds');
var cont = str.innerHTML;
curstring = "twitter: ";
while (cont.indexOf(curstring))
{
replaced = cont.replace(curstring,"TWIMG ");
str.innerHTML = replaced;
}
}
是,当curstring
在cont
中时。在你的while
循环cont
不会改变,所以cont.indexOf(curstring)
将永远是true
。
可能是的。
您的cont.indexOf()
测试应该测试>= 0
,因为如果没有找到,函数返回-1,它计算为真并将导致循环再次进行。
当前仅当cont
以 curstring
开头时终止。
对于其他答案,您也需要覆盖循环内的cont
。
function replace() {
var curstring = "twitter: ";
var str = document.getElementById('feeds');
var cont = str.innerHTML;
var old = cont;
// NB: indexOf() returns -1 on failure, so you
// must compare against that,
while (cont.indexOf(curstring) >= 0) {
cont = cont.replace(curstring, "TWIMG ");
}
// taken outside the loop so we don't modify the DOM
// over and over if the match is repeated - only update
// the DOM if the string got changed
if (cont !== old) {
str.innerHTML = cont;
}
}
有。你从不重新分配内容,也许试试这个?
function replace()
{
var str = document.getElementById('feeds');
var cont = str.innerHTML;
curstring = "twitter: ";
while (cont.indexOf(curstring) != -1)
{
replaced = cont.replace(curstring,"TWIMG ");
str.innerHTML = replaced;
cont = str.innerHTML;
}
}
是cont
在循环中永远不会改变,所以如果cont.indexOf(curstring)
为真,它将永远为真,你的程序将进入一个无限循环
相关文章:
- 使用滚动溢出-x进行无限循环
- 从index.html调用函数,该函数无限循环
- 使用jQuery无限循环播放HTML页面幻灯片
- Grunt任务没有加载,获得无限循环
- 如何在不进入无限循环的情况下将网站重定向到Facebook画布URL
- Backbone+RequireJS+Mediator模式导致视图逻辑短路和无限循环
- jQuery无限循环,动画化许多项目
- 如何避免试图用php+jquery显示php起始页的无限循环
- 6502仿真增强型基本无限循环$C000至$E0ED
- Angular ngRoute导致无限循环和堆栈溢出
- Jquery:无限循环和暂停
- 数组数组:无限循环
- MeteorJS使用流星调用和流星方法时的无限循环
- 如何无限循环数据集字符串
- jquery在无限循环中运行
- 遍历对象会导致无限循环
- 为什么内部Javascript循环会阻止外部循环中断(即无限循环)
- 角度编译指令似乎进入了无限循环
- 我的代码中是否存在无限循环
- 为什么我的 JavaScript 代码中存在潜在的无限循环