【问题标题】:How to add objects dynamically in jquery?如何在jquery中动态添加对象?
【发布时间】:2016-05-06 18:26:49
【问题描述】:

如何在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等处继续赋值

【问题讨论】:

标签: jquery


【解决方案1】:
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++;
        }

【讨论】:

    【解决方案2】:

    我认为以下方法会起作用。直接的. 运算符在这里不起作用。

    使用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++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2012-11-17
      • 2017-04-28
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2016-02-18
      相关资源
      最近更新 更多