咨询JavaScript中while(true)循环的含义及示例代码解析
关于while(true)无限循环的解释
嘿,我来帮你理清楚这段代码里while(true)的作用!
首先,先把你贴的完整代码放出来方便分析:
let str = 'As sly as a fox, as strong as an ox'; let target = 'as'; // let's look for it let pos = 0; while (true) { let foundPos = str.indexOf(target, pos); if (foundPos == -1) break; alert( `Found at ${foundPos}` ); pos = foundPos + 1; // continue the search from the next position }
核心:while(true)是什么?
while(true)是无限循环的标准写法之一。因为true是布尔值里的“真”,这个循环的条件永远成立,所以代码会一遍又一遍执行循环体里的内容——直到碰到break语句主动跳出循环为止。
结合你的代码看逻辑
这段代码是在字符串里找所有target出现的位置,用while(true)的好处是逻辑拆分得很清楚:
- 每次循环里,先从当前
pos位置开始调用indexOf找目标字符串 - 如果返回
-1,说明已经找不到更多匹配项了,就用break跳出这个无限循环,结束整个查找过程 - 如果找到了,就弹出位置,然后把
pos更新为foundPos + 1——这样下一次查找就从当前匹配位置的下一个字符开始,不会重复找到同一个位置
补充:有没有其他写法?
其实你也可以不用while(true),把查找逻辑直接写在while的条件里,比如:
let str = 'As sly as a fox, as strong as an ox'; let target = 'as'; let pos = 0; let foundPos; while ((foundPos = str.indexOf(target, pos)) !== -1) { alert(`Found at ${foundPos}`); pos = foundPos + 1; }
两种写法效果完全一样,只是while(true)的写法把“循环持续”和“终止条件”分开了,有时候在逻辑更复杂的场景下会更易读。
注意点
用while(true)的时候一定要确保循环体里有明确的break条件(就像你代码里的if(foundPos == -1) break),不然循环会一直跑下去,变成死循环,导致程序卡住哦!
内容的提问来源于stack exchange,提问作者st123
相关产品推荐
相关产品推荐

