Javascript:即使我在对象的内部和外部分配了它,对象变量也是空的

时间:2014-09-02 15:52:29

标签: javascript arrays

我正面临以下问题,当我尝试使用javascript中的对象时,我很难在对象内部分配值。特别是this.sItem [i]和oInvoice.sItem [i],它们总是未定义的。

var oInvoice = {
sID: "",
sDate: "",
iNumberOfItems: oSpreadSheetApp.hInvoiceSheet.getRange(SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getActiveCell().getRow(), 2, 1, 1).getValues()[0],
sItem: "",
iRate: "",
iWork: "",
iCalculatedAmount: "",  
sBody: "",
sComment: "",

/* Get the actual data inside range */ 
/* Fetch values for each row in the Range. */
mProcessInvoice: function () {
    var rDataRange = oSpreadSheetApp.hInvoiceSheet.getRange(SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getActiveCell().getRow(), 1, 1, 11);
    var dData = rDataRange.getValues();
    var i = 0;

    /* Read values */ 
    for (i in dData) {
        var rCurrentRow = dData[i]; /* Current row contains values from spreadsheet */

        /* Both this.sItem[i] and oInvoice.sItem[i] are empty */ 
        this.sItem[i] = rCurrentRow[4];
        oInvoice.sItem[i] = rCurrentRow[4];

    }       
}
};

Logger.log(oInvoice.sItem[1]);

我很确定我在这里没有得到一个基本概念,但很乐意期待开悟。

1 个答案:

答案 0 :(得分:0)

一些问题

  1. sItem声明为字符串,将其声明为数组
  2. 使用push方法代替[i],是saffer。
  3. "这"将引用运行代码而不是对象的函数。使用prototype.functionName = function(){}来声明方法,或者不要使用 this ,或者使用Function#call(不推荐,只是告诉你)
  4. 如果您想要连接字符串,只需使用+ =运算符

    var a = '';
    a += 'Hello'
    console.log(a); //"Hello"