You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript数组首尾元素范围验证:按钮切换时限制边界

Fixing Range Validation for First/Last Element Navigation in JavaScript

Got it, let's adjust your code so the navigation stops at the first and last items instead of looping around. Here's what was going wrong with the original code, plus the corrected version:

Issues in the Original Code

  • The Prev() and Next() functions had logic that looped back to the opposite end when hitting the first/last item (e.g., when Current was 0, it jumped to the last index). We need to remove that loop behavior.
  • There was an extra line document.getElementById("textHere").innerHTML = text; that was overriding the initial display of the first item with the entire array as a string—we'll delete that.

Corrected Code

<script type="text/javascript">
  var text = ["first item", "second item", "third item"];
  var Current = 0;

  // Initialize display with the first item
  document.getElementById("textHere").innerHTML = text[Current];

  function Prev() {
    // Only decrement if we're not already at the first item
    if (Current > 0) {
      Current--;
    }
    document.getElementById("textHere").innerHTML = text[Current];
  }

  function Next() {
    // Only increment if we're not already at the last item
    if (Current < text.length - 1) {
      Current++;
    }
    document.getElementById("textHere").innerHTML = text[Current];
  }
</script>

<div id="textHere"></div>
<div>
  <button onclick="Next();">Next!</button>
  <button onclick="Prev();">Previous</button>
</div>

Key Changes Explained

  • Initial Display: We kept the correct line to show the first item on load (text[Current]) and removed the incorrect line that displayed the whole array.
  • Prev() Function: Now it only decreases Current if we're not at index 0. If we are at the first item, nothing changes—so clicking "Previous" won't loop back to the last item.
  • Next() Function: It only increases Current if we're not at the last index (text.length - 1). When at the third item, clicking "Next!" won't jump back to the first item.

This setup ensures the navigation stays within the bounds of your array, stopping at the first and last elements as requested.

内容的提问来源于stack exchange,提问作者G A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:42:33