let str = "as time flies asses start as if there as";
let target = "as";
pos = str.length;
while ((pos = str.lastIndexOf(target, pos-1)) != -1) {
console.log( pos );
if (pos == 0) break; //Why does commenting this causes the infinite loop?
}
如果我们评论
如果(pos == 0)中断;
代码无限运行。为什么会发生这种情况?为什么到达 pos == 0
后代码不会自动停止?
最佳答案
以下是lastIndexOf的参数说明:
Parameter Description item The item to search for start Where to start the search. Negative values will start at the given position counting from the end, and search to the beginning
- 最后一个“真正的”循环结果为 0,因为它在字符串的最开头找到目标。
- 然后用 0-1 调用lastIndexOf。负值会导致从末尾倒退到开头。然后 Pos 再次为 0。
- 返回#1。重复多少次都还是0。
你的问题是 str.lastIndexOf(target, -1)
基本上是一个 indexOf
,所以你在 0 处得到了第一个出现。
无需向您展示工作代码,因为您已经知道:当位置为 0 时退出循环。
关于javascript - 下面的代码使用了lastIndexOf方法。为什么代码到达位置 = 0 后,就开始无限打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60944546/