当我在另一个函数中调用它时,为什么this.contains不是一个函数

时间:2016-06-06 18:47:51

标签: javascript graph

我正在尝试创建一个Graph并一次实现一个方法。我不知道为什么我在调用a.contains(“cats”)后得到此错误'// TypeError:无法读取未定义'的属性'length'。删除所有值后。也许它与this.nodes.splice(i,1)有关?

var Graph = function(){
   this.nodes = [];
   this.edges = {};
};

Graph.prototype.addNode = function(node){
  this.nodes.push(node);
  this.edges[node] = {};
};

Graph.prototype.contains = function(node){
 for(var i = 0; i < this.nodes[i].length; i++){
    if(this.nodes[i] === node){
      return true;
    } else {
      return false;
    }
  }
};

Graph.prototype.removeNode = function(node){

    for(var key in this.edges){
        if(key === node){
          delete this.edges[node];
        }
    }

    for(var i = 0; i < this.nodes.length; i++){
        if(this.nodes[i] === node){
            this.nodes.splice(i,1);
        }
    }

};

var a = new Graph();
a.addNode("cats");
a.addNode("dogs");
a.contains("cats");
a.removeNode("dogs");
a.contains("cats");
a.removeNode("cats");
a.contains("cats"); //TypeError: Cannot read property 'length' of undefined

1 个答案:

答案 0 :(得分:1)

您需要更改

for (var i = 0; i < this.nodes[i].length; i++)

    for (var i = 0; i < this.nodes.length; i++)