【问题标题】:Why doesn't the nested loop go through the property of object which is an array?为什么嵌套循环不通过作为数组的对象的属性?
【发布时间】:2021-03-15 16:14:59
【问题描述】:

我正在尝试删除图中顶点的边缘,但是 removeVertex() 方法中的嵌套循环 不会通过顶点来移除特定的边。

 class graph{
   constructor(){
       this.adjacencyList = {
       }
   }

   addvertex(vertex){
       this.adjacencyList[vertex] = []    
   }
   addEdge(v1,v2,edge){
       this.adjacencyList[v1].push(v2);
        this.adjacencyList[v2].push(v1);  
   }

   

   removeVertex(vertex){
       for( let property in this.adjacencyList){
            for( let i = 0 ; i++ ; i < [property].length){
                 console.log([property][i])
                   }
            }
          
       }
      
   }

【问题讨论】:

  • this.adjacencyList[property].length 而不是[property].length

标签: javascript algorithm loops graph


【解决方案1】:

你犯了两个错误:

  • for 的一般语法是 for(initialization; condition; increment/decrement)。您需要将第二个数字的条件和i++ 放在最后。
  • 第二个错误是您正在访问length 一个新创建的数组,它只包含一个成员。所以它总是会返回1。您需要从对象访问属性,然后获取其长度

这样

this.adjacencyList[property].length;


removeVertex(vertex){
   for( let property in this.adjacencyList){
        for( let i = 0 ; i < this.adjacencyList[property].length; i++){
             console.log(this.adjacencyList[property][i])
        }
   }
      
}
  

【讨论】:

  • 我做到了,但它仍然没有显示任何内容
  • @PərvizPiri 然后你需要显示我可以测试的最小代码。
【解决方案2】:

这可能对你有帮助

    class Graph {
      constructor() {
        this.adjacencyList = {};
      }

      addVertex(v) {
        this.adjacencyList[v] = [];
      }
      addEdge(v1, v2) {
        this.adjacencyList[v1].push(v2);
        this.adjacencyList[v2].push(v1);
      }

      removeVertex(v) {
        // remove vertex v from adjacencyList keys
        Reflect.deleteProperty(this.adjacencyList, v);
        // // remove all agdes related to vertex
        for (let key of Object.keys(this.adjacencyList)) {
          for (let edge of this.adjacencyList[key]) {
            if (edge === v) {
              let index = this.adjacencyList[key].indexOf(edge);
              this.adjacencyList[key].splice(index, 1);
            }
          }
        }
      }
    }

    let g = new Graph();
    // add 3 Vertexes
    g.addVertex("A");
    g.addVertex("B");
    g.addVertex("C");
    // add three adges
    g.addEdge("A", "B");
    g.addEdge("A", "C");
    g.addEdge("B", "C");
    // remove adges "C"
    g.removeVertex("C");

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 2018-01-16
    • 2021-12-09
    • 1970-01-01
    • 2021-07-24
    • 2013-07-28
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多