当前,您的对象文字创建一个具有两个属性的对象,currentActiveCategories是一个数组, 和currentValue,它设置为在addValues() 评估对象文字时调用的结果。您正在尝试使用 调用该函数this.currentActiveCategories,这将是undefined,因为this此时不等于该对象。
如果想法是有一个可以随时返回当前总数的函数,您可以这样做:
var primaryCare = {
currentActiveCategories : [ "1", "2"],
currentValue : function () {
var tempTotal = "";
for(var i = 0; i < this.currentActiveCategories.length; i++){
tempTotal += this.currentActiveCategories[i];
}
return tempTotal;
}
}
primaryCare.currentValue(); // returns "12", i.e., "1" + "2"
始终声明变量,var否则它们将成为全局变量 - 请注意,您不能int在 JS 中声明变量。在开始向其添加字符串之前,您需要初始化tempTotal为一个空字符串,否则"12"您将得到"undefined12".
当您将函数作为对象的方法调用时,就像primaryCare.currentValue()(如上所示)然后在函数内this将设置为该对象。
将值添加为字符串对我来说似乎有点奇怪。如果您想使用数字并获得数字总数,您可以这样做:
var primaryCare = {
currentActiveCategories : [ 1, 2], // note no quotes around the numbers
currentValue : function () {
var tempTotal = 0;
for(var i = 0; i < this.currentActiveCategories.length; i++){
tempTotal += this.currentActiveCategories[i];
}
return tempTotal;
}
}