创建更新对象字段的函数的正确方法是什么?下面的方式,似乎什么也没发生:
function adjmatrix(neighbors){
this.neighbors = neighbors
this.sum = 0
}
adjmatrix.prototype.update = function(){
this.neighbors.forEach(function(a){a.sum += 10})
}
var myMatrix = new adjmatrix([1,2,3])
myMatrix.update()
print(myMatrix.sum) //Expect a value of 30, I get 0.
对 Javascript 有点陌生,所以我不太清楚范围和内容是如何工作的。感谢您的帮助。我正在命令行中通过 d8
运行我的编程。
最佳答案
为了更新对象的“sum”属性,您的“update”方法应如下所示:
adjmatrix.prototype.update = function(){
var matrix = this;
this.neighbors.forEach(function(a){matrix.sum += 10})
}
如果您想对“邻居”值求和,则如下所示:
adjmatrix.prototype.update = function(){
var matrix = this;
this.neighbors.forEach(function(a){ matrix.sum += a; })
}
.forEach()
调用传入数组的每个值,每次调用该函数一个值。
关于更新对象字段的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24435163/