如何在jquery中动态添加对象?

时间:2016-01-29 05:19:45

标签: jquery

如何生成变量并动态分配内部for循环?

例如,

var tempClosingBalance, k = 1;
for (var i = 0; i < customArray.length; i++) {
    tempClosingBalance = "ClosingBalanceWithType" + k;
    for (var j = 0; j < output.length; j++) {
        output[j].tempClosingBalance = customArray[i][j].ClosingBalanceWithType;
    }
    k++;
}

此处tempClosingBalance变量包含ClosingBalanceWithType1并分配值,相同条件继续在ClosingBalanceWithType2ClosingBalanceWithType3中分配值等。

2 个答案:

答案 0 :(得分:0)

我认为以下内容可行。直接.运算符不适用于此处。

使用output[j]["ClosingBalanceWithType" + k]

var tempClosingBalance, k = 1;
for (var i = 0; i < customArray.length; i++) {
    tempClosingBalance = "ClosingBalanceWithType" + k;
    for (var j = 0; j < output.length; j++) {
        output[j][tempClosingBalance] = customArray[i][j].ClosingBalanceWithType;
    }
    k++;
}

答案 1 :(得分:0)

for (var i = 0; i < customArray.length; i++) {
            for (var j = 0; j < output.length; j++) {
                output[j]["ClosingBalanceWithType" + k] = customArray[i][j].ClosingBalanceWithType;
                output[j]["TransactionCount" + k] = customArray[i][j].TransactionCount ? customArray[i][j].TransactionCount : 0;
                output[j]["AmountType" + k] = customArray[i][j].AmountType;
            }
            k++;
        }