javascript - 下面的代码使用了lastIndexOf方法。为什么代码到达位置 = 0 后,就开始无限打印?

标签 javascript

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
  1. 最后一个“真正的”循环结果为 0,因为它在字符串的最开头找到目标。
  2. 然后用 0-1 调用lastIndexOf。负值会导致从末尾倒退到开头。然后 Pos 再次为 0。
  3. 返回#1。重复多少次都还是0。

你的问题是 str.lastIndexOf(target, -1) 基本上是一个 indexOf,所以你在 0 处得到了第一个出现。

无需向您展示工作代码,因为您已经知道:当位置为 0 时退出循环。

关于javascript - 下面的代码使用了lastIndexOf方法。为什么代码到达位置 = 0 后,就开始无限打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60944546/

相关文章:

javascript - Angular 插件 ZeroClipboard 不工作

页面加载和 Bootstrap 进度条上的 Javascript 计时问题

javascript - 导航到时,Android/WebView 不会加载 javascript 库图像

javascript - Angularjs View 不更新,单击按钮时 View 闪烁

php - 将 PHP 输出传递给 jQuery

javascript - 如何防止 transitionend 事件被运行两次

javascript - <p :selectCheckboxMenu is not fired when selecting all 中的 onchange 事件

javascript - 使用 overflow-x 在 div 中设置 x 滚动位置的纯 javascript 方法

javascript - WP CSS & JS 不排队

JavaScript google maps API - 一次打开一个信息窗口..