let str = 'As sly as a fox, as strong as an ox';
let target = 'as'; // 这是我们要查找的目标
let pos = 0;
while (true) {
let foundPos = str.indexOf(target, pos);
if (foundPos == -1) break;
alert( `Found at ${foundPos}` );
pos = foundPos + 1; // 继续从下一个位置查找
}
有个疑问是,这里的
while (true) {
...
...
}
感觉应该是个无限循环,但实际不是,为什么呢?
麻烦高手给解释下,谢谢~
这段程序能够在下标为
7
、17
、27
时找到我们需要的target
。当alert
Found at 27
之后,pos
变成28,这时再去执行let foundPos = str.indexOf(target, 28);
founPos
就会变成 -1,继续执行,到达break。所以就跳出循环了。
while()
括号中的内容是条件体,符合条件继续循环。但是遇到break
就会跳出当前循环体了。