jQuery push()进入数组的奇怪行为

时间:2014-05-31 20:41:27

标签: javascript jquery arrays

我试图将一些元素推入二维数组 我正在使用的代码是:

samount.push ({
        "value": val, 
        "currency": currency
    });

我试图推入samount的数组是这样的:

groupedArray = 
     [{value: 100, currency: 'EUR'},
      {value: 100, currency: 'EUR'},
      {value: 100, currencu: 'EUR'}]

实际上,上面的数组表示一个表的行,并且在每行单击时,push()函数正在为samount数组添加一个新元素

点击两次后,samount数组看起来像:

samount = 
     [{value: 100, currency: 'EUR'},
      {value: 100, currency: 'EUR'}]

在第三行单击,数组变为:

samount = 
     [{value: 200, currency: 'EUR'},
      {value: 100, currency: 'EUR'},
      {value: 100, currencu: 'EUR'}]

我必须提到我的代码里面没有总和,所以push()函数对第一个元素的值进行求和并将它们添加到数组中是非常奇怪的

你知道push()函数是否可以将元素添加到这种类型的数组中?

完整的代码是:

"fnDrawCallback": function (oSettings) {  
    var $dt = $('#dt_debts').footable({  
     breakpoints: { // The different screen resolution breakpoints  
         phone: 320,  
         tablet: 768  
     }   
    });  
    $dt.trigger('footable_resize');  

    var amount      = new Array();
    var samount     = new Array();  

    $('#dt_debts tbody tr ').each( function () {                            
        var iPos = oTable.fnGetPosition( this );
        if (iPos!=null) {
            var aData = oTable.fnGetData( iPos );
            if (jQuery.inArray(aData[0], selected)!=-1) {
                $(this).addClass('row_selected');
                $(this).find( 'td input:checkbox' ).attr('checked', 'checked');
            }
        }
        $(this).click( function (e) {   
            e.preventDefault();                     
            var iPos = oTable.fnGetPosition( this );
            var aData = oTable.fnGetData( iPos );
            var iId = aData[0];
            is_in_array = jQuery.inArray(iId, selected);
            if (is_in_array==-1) {
                selected[selected.length]=iId;
            }
            else {
                selected = jQuery.grep(selected, function(value) {
                    return value != iId;
                });
            }
            if ( $(this).hasClass('row_selected') ) {
                console.info('>>> Operatie de eliminare');
                $(this).removeClass('row_selected');
                $(this).find( 'td input:checkbox' ).prop('checked', false);
                if ($(aData[0]).data('typo') == "t-0") {
                    val = parseFloat(aData[9].split(" ")[0]);
                    currency = aData[9].split(" ")[1];
                    if (currency != '') {
                        $.each(amount, function(idx, item) {
                            if (item.currency == currency && item.value == val) {
                                amount.splice(idx, 1); // Remove current item
                                return false; // End the loop
                            }
                        });
                    }
                } else if ($(aData[0]).data('typo') == "t-1") {
                    val = parseFloat(aData[10].split(" ")[0]);
                    currency = aData[10].split(" ")[1];
                    if (currency != '') {
                        $.each(samount, function(idx, item) {
                            if (item.currency == currency && item.value == val) {
                                samount.splice(idx, 1); // Remove current item
                                return false; // End the loop
                            }
                        });                                 
                    }                                       
                }
                console.info(amount);
                console.info(samount);
            } else {
                console.info('>>> Operatie de adaugare');
                $(this).addClass('row_selected');                                   
                $(this).find( 'td input:checkbox' ).attr('checked', 'checked');

                if ($(aData[0]).data('typo') == "t-0") {
                    val = parseFloat(aData[9].split(" ")[0]);
                    currency = aData[9].split(" ")[1];
                    if (currency != '') {
                        amount.push ({
                                "value": val, 
                                "currency": currency
                            });
                    }       
                } else if ($(aData[0]).data('typo') == "t-1") {
                    val = parseFloat(aData[10].split(" ")[0]);
                    currency = aData[10].split(" ")[1];
                    if (currency != '') {
                        samount.push ({
                                "value": val, 
                                "currency": currency
                            });
                    }       
                }
                console.info(amount);
                console.info(samount);                                  
            }
}

Aftre花费数小时搜索错误,我发现错误出现在这部分代码中:

var objects1 = new Array();
objects1 = samount;
var categories1 = new Array();
var groupedObjects1 = [];
var i = 0;

_.each(objects1,function(obj){
    var existingObj;

    if($.inArray(obj.currency,categories1) >= 0) {
        existingObj = _.find(objects1,function(o){return o.currency === obj.currency;});
        existingObj.value += obj.value;
    } else {
        groupedObjects1[i] = obj;
        categories1[i] = obj.currency;
        i++;
    }
});// JavaScript Document

实际上,即使我已经声明了一个用于使用循环的新数组,似乎 samount 数组也被修改了。我不明白为什么循环正在修改初始数组,即使我没有使用它

2 个答案:

答案 0 :(得分:1)

是的,推进很好。事实上,我测试了它,它的工作原理应该如此。我假设正在发生的是在其他地方修改的值 - 因为你将一个对象推入具有值val的数组中,所以数组只能保存对整个事物的引用它代表的价值。

只是为了说明这个

var val = { "value" : 100 };
var storage = [ ];

storage.push(val);


console.log("value  : " + val.value);
console.log("value in storage : " + storage[0]["value"]);

val.value = 200;

console.log("value  : " + val.value);
console.log("value in storage : " + storage[0]["value"])

产量

value  : 100
value in storage : 100
value  : 200
value in storage : 200

JavaScript中的变量是基元的值(例如整数)传递,但是通过对象的引用传递。

答案 1 :(得分:1)

您可以使用.join()代替.push()

 //if you want the ful array as a single element:
    groupedArray = 
         [{{value: 100, currency: 'EUR'},
          {value: 100, currency: 'EUR'},
          {value: 100, currencu: 'EUR'}}];

    samount.join(groupedArray);


//if you want each element in groupedArray as elements in samount:
groupedArray = 
     [{value: 100, currency: 'EUR'},
      {value: 100, currency: 'EUR'},
      {value: 100, currencu: 'EUR'}];

samount.join(groupedArray);