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()andNext()functions had logic that looped back to the opposite end when hitting the first/last item (e.g., whenCurrentwas 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 decreasesCurrentif 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 increasesCurrentif 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
相关产品推荐
相关产品推荐

