簡體   English   中英

數組在對象文字表示法中添加函數

[英]array adding function in object literal notation

這是我正在使用的代碼,不太確定如何使用文字符號,我必須以某種方式將currentActiveCategories傳遞給函數。 不確定這是否是首選的方法,不想學習壞習慣。

var primaryCare = {
    currentActiveCategories : [ "1", "2"],
    currentValue : addValues(this.currentActiveCategories)
}

function addValues(activeCategories) {
    tempTotal;
    for(int i = 0; i < activeCategories.length; i++){
        tempTotal += activeCategories[i];
    }
    return tempTotal;
}

目前你的對象字面創建具有兩個屬性,對象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聲明你的變量或者它們將變成全局變量 - 請注意你不能在JS中聲明一個int 在開始向其添加字符串之前,需要將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;
                   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM