在 JavaScript 中添加图中的节点不完美。

huangapple go评论71阅读模式
英文:

Add nodes in a Graph not working perfectly in js

问题

我已经创建了一个包含键值对的图表,其中键是节点编号,值是邻接边的数组,这里我编写了一个函数,将节点和邻接边添加到图表中,但是这个函数在这里不起作用,我应该修改什么地方,以便获得类似这样的图表:{ 1:[2,4],2:[1,3],3:[2,4],4:[1,4],5:[3,4]}
给定的代码如下:

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

function addNode(key, value = []) {
    graph[key] = value;
}

addNode(5, [3, 4]);
console.log(graph);
英文:

I have created a graph which containing key and value pair ,key is for node number and value for adjacency list value which is an array of adjacent edges, here I wrote a function that will add the node and adjacency edges in the graph, but here the function is not working ,which thing should I have to modified here that I want graph like { 1:[2,4],2:[1,3],3:[2,4],4:[1,4],5:[3,4]}
code is given below

var graph = {
    1: [2, 4],
    2: [1, 3],
    3: [2, 4],
    4: [1, 4]
  };
  function addNode(key, value = []) {
    graph[key].push({ value: value });
  }
  addNode(5, [3, 4]);
  console.log(graph);

答案1

得分: 1

function addNode(key, value = []) {
  graph[key] = value;
}

或者,如果您要给已存在的节点添加新值:

function addNode(key, values = []) {
  (graph[key] ??= []).push(...values);
}

试试看:

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

function addNode(key, value = []) {
  graph[key] = value;
}

function addValuesToNode(key, value = []) {
  (graph[key] ??= []).push(...value);
}

addNode(5, [3, 4]);
console.log(graph);

addValuesToNode(5, [1]);
console.log(graph);
英文:
function addNode(key, value = []) {
  graph[key] = value;
}

Or, if you want to add new values to the node, given it already existed:

function addNode(key, values = []) {
  (graph[key] ??= []).push(...values);
}

Try it:

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

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

function addNode(key, value = []) {
  graph[key] = value;
}

function addValuesToNode(key, value = []) {
  (graph[key] ??= []).push(...value);
}

addNode(5, [3, 4]);
console.log(graph);

addValuesToNode(5, [1]);
console.log(graph);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月12日 15:25:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定