我有这个代码,允许我返回一个关于连接到特定帖子的帖子的字符串。我试图在列表部分(list=list+this["connectionsTo"[i]].postNum+"\n";
)中访问下面的属性时使用括号和点表示法,但不起作用。但是当我使用双点符号时,它有效,为什么?我相信那两个是一样的。
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());
答案 0 :(得分:5)
由于您正在迭代this.connectionsTo
数组,因此您正在寻找
this["connectionsTo"][i]
this.connectionsTo[i]
而不是
this["connectionsTo"[i]]
为字符串编制索引,然后将该字符作为this
的属性。