Javascript推送对象中的数组项

时间:2014-06-10 14:16:58

标签: javascript arrays object

我在Javascript中创建对象有以下问题

当用户点击按钮时,我想将sn_slab推送到数组板。但是每个serial_number都按batch_number分组。

对象应该看起来像这样

    var Object = {
    'COFBP21018': {
        slabs: {
            0: 18765,
            1: 38947,
            ...
        }
    },
    'DEPOUS394O': {
        slabs: {
            0: 11006276,
            1: 11020446,
                    ...

        }
    },
    ..
}

我的html看起来像这样

<a href=".." class="add_slab_to_array" data-batch_nr="COFBP21018" data-sn_slab="18765" />
<a href=".." class="add_slab_to_array" data-batch_nr="COFBP21018" data-sn_slab="38947" />
<a href=".." class="add_slab_to_array" data-batch_nr="DEPOUS394O" data-sn_slab="11006276" />
<a href=".." class="add_slab_to_array" data-batch_nr="DEPOUS394O" data-sn_slab="11020446" />

var block = {};
$('.add_slab_to_array').click(function(event) {
        event.preventDefault();

        var batch_nr = $( this ).attr('data-batch_nr');
        var sn_slab = $( this ).attr('data-sn_slab');

        // Create new object if batch_nr does not exists
        // ADD sn_slab to Array inside the Object with related batch_nr

      block[batch_nr] = {
           slabs: [],
           add: function(sn_slab) {
               this.slabs.push(sn_slab)
           }
       }

       block[batch_nr].add(sn_slab);

 });

上面的代码有效,但我的数组板总是被覆盖。

2 个答案:

答案 0 :(得分:2)

在我看来,每次点击都会重新定义块对象。您应该在继续之前检查它是否已设置。

block[batch_nr] = block[batch_nr] || {};

block[batch_nr].slabs = block[batch_nr].slabs || [];

block[batch_nr].add = block[batch_nr].add || function(sn_slab) {                         
            this.slabs.push(sn_slab);
           };

答案 1 :(得分:0)

考虑一下

     block[batch_nr] = {
       slabs: [],
       add: function(sn_slab) {
           if (block[batch_nr]) {
               block[batch_nr].slabs.push(sn_slab)
           }
       }
   }