【问题标题】:How to :Retrieve & check nested Objects in an Array如何:检索和检查数组中的嵌套对象
【发布时间】:2021-12-31 08:31:27
【问题描述】:

最近几天我无法解决以下问题。

所以我有一个名为“Nodes”的类,它具有属性 Neighbors - 这是一个数组。

当我将节点(节点 B)作为“邻居”插入到邻居数组中时,它必须是类邻居的实例,它将节点 B 的实例作为参数一个“对立节点”。

现在我必须创建一个语句来检查节点 A 和 B 之间的连接是否已经存在

最好的方法是什么?我遇到了解构方法,但我不确定这是否适合这项任务。

class Node {
  constructor(nodeName) {
    this.nodeName = nodeName;
    this.neighbours = [];
  }
};

class Neighbour {
  constructor(oppositeNode, weight = null) {
    this.oppositeNode = oppositeNode;
    this.weight = weight;
  }
};

nodea = new Node(a);
nodeb = new Node(b);
nodea.neighbours.push(new Neighbour(nodeb));

所以我想写的语句如下:

伪代码

如果(节点 A 在节点 A.neighbours 中有节点 B){x}

提前致谢

【问题讨论】:

    标签: javascript arrays nested javascript-objects


    【解决方案1】:

    下面是您的脚本的延续,使用find 方法进行检查:

    class Node {
      constructor(nodeName) {
        this.nodeName = nodeName;
        this.neighbours = [];
      }
    };
    
    class Neighbour {
      constructor(oppositeNode, weight = null) {
        this.oppositeNode = oppositeNode;
        this.weight = weight;
      }
    };
    
    nodea = new Node("a");
    nodeb = new Node("b");
    nodea.neighbours.push(new Neighbour(nodeb));
    
    let neighbour = nodea.neighbours.find(neighbour => neighbour.oppositeNode == nodeb);
    
    if (neighbour) console.log("found neighbor. It has weight " + neighbour.weight);
    else console.log("not found");

    【讨论】:

    • 太棒了,非常感谢 :) 也尝试了 array.find 方法,但把最后一部分搞砸了 ^^ 幸好我至少接近了 ^^
    猜你喜欢
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2021-11-04
    • 2012-06-24
    相关资源
    最近更新 更多