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

JS中删除图节点功能异常,求修正以实现预期图结构

问题分析与修复方案

原代码的核心问题

  1. splice参数错误:splice(key, 1)中的第一个参数是数组索引,而非要删除的元素值。graph[3]的邻接数组是[2,4],不存在索引3,所以这行代码完全无效。
  2. 未删除目标节点本身:要删除节点3,需要直接从graph对象中移除3这个键,而非修改它的邻接边数组。
  3. 未清理其他节点的邻接边:删除节点3后,其他节点的邻接边中若包含3,也需要一并移除(比如原graph[2]中的3)。

修改后的代码

var graph = {
    1: [2, 4],
    2: [1, 3],
    3: [2, 4],
    4: [1, 4]
};

function deleteNode(key) {
    // 检查节点是否存在,不存在直接返回
    if (!graph[key]) return;

    // 遍历所有节点,移除邻接边中的目标节点
    Object.keys(graph).forEach(node => {
        const adjacencyList = graph[node];
        const targetIndex = adjacencyList.indexOf(key);
        if (targetIndex !== -1) {
            adjacencyList.splice(targetIndex, 1);
        }
    });

    // 从图对象中彻底删除目标节点
    delete graph[key];
}

deleteNode(3);
console.log(graph);

说明

  • 遍历所有节点的邻接表,用indexOf定位目标节点的位置,再通过splice删除,确保所有指向被删节点的边都被清理。
  • 使用delete操作符直接移除graph中的目标节点键,完成节点的彻底删除。

执行后得到的正确图结构为:

{ 1: [2, 4], 2: [1], 4: [1, 4] }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:25:26