首页 > 解决方案 > 如何使这个javascript数组值循环并在最后一个索引处停止

问题描述

我有这个脚本,它从 javascript 数组中一次计算一个值,但问题是当它计数到最后一个索引时,它再次从索引 0 开始,但我希望它在最后一个索引处停止。我正在使用 setInterval 使其继续运行。到目前为止,这是我的代码:感谢您的宝贵时间。谢谢

<!DOCTYPE html>
<html>

<head>
  <title>my page</title>
</head>

<body>
  <h4>Counter</h4>
  <span id="disp"></span>

  <script>
    var title = ['$0', '$30', '$47', '$257', '$657', '$1389', '$1557', '$2557'];

    var i = 0; // the index of the current item to show

    setInterval(function() { // setInterval makes it run repeatedly
      document
        .getElementById('disp')
        .innerHTML = title[i++]; // get the item and increment i to move to the next
      if (i == title.length) i = 0; // reset to first element if you've reached the end
    }, 3000);
  </script>
</body>

</html>

标签: javascripthtmlarrayssetinterval

解决方案


您可以存储间隔 id,如果您完成调用clearInterval它来停止间隔。

<h4>Counter</h4>

<span id="disp"></span>

<script>
  var title = ['$0', '$30', '$47', '$257', '$657', '$1389', '$1557', '$2557'];

  var i = 0; // the index of the current item to show

  var interval = setInterval(function() { // setInterval makes it run repeatedly
    document
      .getElementById('disp')
      .innerHTML = title[i++]; // get the item and increment i to move to the next
    if (i == title.length) {
      i = 0; // reset to first element if you've reached the end
      clearInterval(interval);
    }
  }, 300);
</script>


推荐阅读