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

如何停止脚本执行?实现数组耗尽后点击按钮无操作

解决数组耗尽后点击按钮不再执行操作的问题

问题说明

当前脚本需要实现点击按钮逐个添加数组中的数字,当数组元素耗尽后,点击按钮不执行任何操作。但现有代码在数组元素耗尽后继续点击会显示undefined,需要修复。

原代码问题分析

  1. 索引操作顺序错误:点击事件中先递增currentIndex再取数组元素,当currentIndex等于数组长度时,numbers[currentIndex]会返回undefined
  2. 判断逻辑错误:用赋值运算符=代替比较运算符===,且错误地判断node对象而非其文本内容,同时event.stopPropagation()无法阻止当前函数执行,它只是阻止事件冒泡

修正后的代码

JavaScript 代码

let numbers = [1, 2, 3, 4, 5];
let paragraph = document.querySelector('p');
let currentIndex = 0;
paragraph.innerHTML = numbers[currentIndex];

let button1 = document.querySelector('button');
button1.onclick = function() {
  // 先判断是否已经到数组最后一个元素
  if (currentIndex >= numbers.length - 1) {
    return; // 终止函数执行,不做任何操作
  }
  
  currentIndex += 1;
  let node = document.createTextNode(", " + numbers[currentIndex]);
  paragraph.appendChild(node);
}

HTML 代码

<title>Hidden numbers</title>
<p></p>
<button>Show next number</button>

修正逻辑说明

  • 在点击事件开头增加判断:当currentIndex已经是数组最后一个元素的索引(numbers.length - 1)时,直接返回,不执行后续添加操作
  • 调整索引递增时机,确保每次取到的都是数组中存在的有效元素,避免出现undefined

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:25:14