![](/img/trans.png)
[英]I want to call a function on onclick but that function should be inside another function
[英]Why this.contains not a function when I call it inside another function
我正在尝试制作一个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
你需要改变
for (var i = 0; i < this.nodes[i].length; i++)
至
for (var i = 0; i < this.nodes.length; i++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.