Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

while相关

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) {
...
...
}
感觉应该是个无限循环,但实际不是,为什么呢?
麻烦高手给解释下,谢谢~


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这段程序能够在下标为71727时找到我们需要的target
当alertFound at 27之后,pos变成28,这时再去执行let foundPos = str.indexOf(target, 28);
founPos就会变成 -1,继续执行,到达break
所以就跳出循环了。

while()括号中的内容是条件体,符合条件继续循环。但是遇到break就会跳出当前循环体了。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...