JavaScript随机抽取任务列表遍历完成后未终止问题求助
问题诊断
代码存在三个核心问题:
- 执行报错导致数组元素从未被删除:
taskList.shift(Math.value());这行存在语法错误,Math对象不存在value()方法,执行到此处时会直接抛出异常,中断当前函数执行,taskList的元素永远不会被移除,因此每次点击抽取按钮都会从原始数组中随机取数,出现无限循环的问题。 - 删除逻辑不符合业务需求:即便移除不存在的
Math.value()调用,Array.shift()方法的作用是固定删除数组的第一个元素,而非刚刚随机抽到的对应下标的元素,会导致已经抽到的任务没有被移除,后续仍会被重复抽取,不符合「抽过的任务不再出现」的要求。 - 代码逻辑冗余:
showNextTask函数内写了两次相同的空数组判断逻辑,没有必要。
修复方案
调整showNextTask函数的逻辑:生成随机下标后先取出对应任务,再用Array.splice()方法删除该下标对应的元素,同时移除无效代码和冗余判断。另外原代码中添加任务的逻辑也可以改用更语义化的push方法实现。
修复后的完整代码如下:
var taskList = []; var $ = function(id) { return document.getElementById(id); } var listTasks = function() { let textList = ""; for (var i in taskList) { textList += taskList[i] + "\n"; } $("task_list").value = textList; } var addTask = function() { taskList.push($("new_task").value); $("new_task").value = ""; $("new_task").focus(); listTasks(); } var showNextTask = function() { if (taskList.length == 0) { alert("No tasks in the list"); $("next_task").value = ""; return; } const randomIndex = Math.floor(Math.random() * taskList.length); const selectedTask = taskList[randomIndex]; taskList.splice(randomIndex, 1); $("next_task").value = selectedTask; }; window.onload = function() { $("add_task").onclick = addTask; $("show_next_task").onclick = showNextTask; $("new_task").focus(); }
内容的提问来源于stack exchange,提问作者knowledgeseeker
相关产品推荐
相关产品推荐

