Reputation:
I have this code that allows me to return a string about the posts connected to a particular post. I tried to use the bracket and dot notation in accessing properties below in the list part (list=list+this["connectionsTo"[i]].postNum+"\n";
) but doesn't work. But then when I used the double dot notation, it worked, why? I believe those two are the same.
function Fencepost(x, y, postNum) {
this.x = x;
this.y = y;
this.postNum = postNum;
this.connectionsTo = [];
}
Fencepost.prototype = {
sendRopeTo: function(connectedPost) {
this.connectionsTo.push(connectedPost);
},
removeRope: function(removeTo) {
var temp = [];
for (var i = 0; i < this.connectionsTo.length; i++) {
if (this.connectionsTo[i].postNum != removeTo) {
temp.push(this.connectionsTo[i]);
}
}
this.connectionsTo = temp;
},
movePost: function(x, y) {
this.x = x;
this.y = y;
},
valueOf: function() {
return Math.sqrt(this.x * this.x +
this.y * this.y);
}
};
Fencepost.prototype.toString=function(){
var list="";
for(var i=0;i<this.connectionsTo.length;i++){
list=list+this["connectionsTo"[i]].postNum+"\n";
}
return "Fence post #"+this.postNum+":\nConnected to posts:\n"+list+"Distance from ranch: "+this.valueOf()+" yards";
};
var post10=new Fencepost(3,4,10);
var post11=new Fencepost(5,7,11);
var post12=new Fencepost(6,7,12);
var post13=new Fencepost(8,9,13);
post10.sendRopeTo(post11);
post10.sendRopeTo(post12);
post10.sendRopeTo(post13);
console.log(post10.toString());
Upvotes: 0
Views: 127
Reputation: 664385
Since you are iterating over the this.connectionsTo
array, you are looking for
this["connectionsTo"][i]
this.connectionsTo[i]
instead of
this["connectionsTo"[i]]
which indexes the string, and then takes that character for the property of this
.
Upvotes: 4