JS:在对象中添加值

时间:2014-10-14 23:52:06

标签: javascript jquery

expire,target和quoted变量将始终为数字。我想要计算每一个。

如何获取total['expire']对象中的当前total = {}?我想我可能会以错误的方式解决这个问题。

data = [];
$('tr.count').each(function(i) {

    var self = $(this),
        expire = self.find('td:nth-of-type(2) input').val(),
        target = self.find('td:nth-of-type(3) input').val(),
        quoted = self.find('td:nth-of-type(4) input').val();

        data[i] = {
            expire : expire,
            target : target,
            quoted : quoted,
        };

        total = {
            expire : expire, // in php I would do 'expire' += $expire;
            target : target,
            quoted : quoted,
        };

});

1 个答案:

答案 0 :(得分:1)

定义总外部并在内部增加。

data = [];
total = {
    expire : 0,
    target: 0,
    quoted: 0
};
$('tr.count').each(function(i) {

    var self = $(this),
        expire = self.find('td:nth-of-type(2) input').val(),
        target = self.find('td:nth-of-type(3) input').val(),
        quoted = self.find('td:nth-of-type(4) input').val();

        data[i] = {
            expire : expire,
            target : target,
            quoted : quoted,
        };

        total.expire += expire;
        total.target += target;
        total.quoted += quoted;

});