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

JS数组splice删数异常排查与二分查找功能实现咨询

问题修复与功能实现

splice多删数据问题修复

原Remove_Athlete函数存在3个逻辑错误:

  • 直接将用户输入的姓名字符串作为splice的索引参数,person - 1计算结果为NaN,splice接收到NaN作为起始索引时会默认从数组第0位开始删除
  • 遍历数组执行删除操作后没有终止循环,数组长度随删除操作变化后,循环会重复触发splice,导致多删数据
  • 逻辑未做姓名匹配,不管用户输入什么都会执行删除,不符合按姓名删除的需求

修复后代码:

function Remove_Athlete() {
    const targetName = prompt("Enter the name to remove the Athlete")?.trim();
    if (!targetName) return;
    const targetIndex = athlete_name.findIndex(name => name === targetName);
    if (targetIndex === -1) {
        alert(`未找到名为${targetName}的运动员`);
        return;
    }
    athlete_name.splice(targetIndex, 1);
    athlete_height.splice(targetIndex, 1);
    alert(`已删除运动员${targetName},当前姓名列表:${athlete_name},身高列表:${athlete_height}`);
    Display_Athlete();
}

二分查找功能实现

实现要求:替换原有顺序遍历的查找逻辑,二分查找执行前必须先对数组排序,排序过程需保持姓名、身高两个数组的索引对应关系,避免数据错位。

二分查找仅对有序数组生效,因此查找前需要先对运动员数据按姓名排序,排序时通过合并关联数组的方式保证姓名和身高的对应关系不混乱,完整实现代码如下:

// 按姓名升序排序关联数组,保证姓名、身高索引一一对应
function sortAthleteData() {
    const combined = athlete_name.map((name, idx) => ({
        name,
        height: athlete_height[idx]
    }));
    combined.sort((a, b) => a.name.localeCompare(b.name));
    for (let i = 0; i < combined.length; i++) {
        athlete_name[i] = combined[i].name;
        athlete_height[i] = combined[i].height;
    }
}

function Binary_Search() {
    const targetName = prompt("Enter the name to Find the Athlete")?.trim();
    if (!targetName) return;
    // 查找前先排序
    sortAthleteData();
    // 二分查找核心逻辑
    let left = 0;
    let right = athlete_name.length - 1;
    let findIndex = -1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        const compareResult = athlete_name[mid].localeCompare(targetName);
        if (compareResult === 0) {
            findIndex = mid;
            break;
        }
        // 中间值小于目标值,检索右半区间
        if (compareResult < 0) left = mid + 1;
        // 中间值大于目标值,检索左半区间
        else right = mid - 1;
    }
    // 渲染结果
    let text = "";
    if (findIndex !== -1) {
        text = `<hr/>Athlete No - ${findIndex + 1},  Athlete Name is  ${athlete_name[findIndex]}   and height is ${athlete_height[findIndex]}<br>`;
    } else {
        alert(`${targetName} Invalid Athlete name`);
    }
    document.getElementById("message").innerHTML = text;
}

页面新增二分查找按钮时,直接给按钮绑定onclick="Binary_Search()"即可,和原有功能按钮的绑定方式一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 20:51:25