子数组和推送数据

sub array and push data

本文关键字:数据 数组      更新时间:2023-09-26

你好,我正在尝试创建一个动态数组,但我遇到了问题,我有一个onclick事件来创建发票,所以当单击时启动并且我有它

var $boletos=new Array();
function onclick(value){
     if($invoice.length==0){
       $invoice.push({"items":{}}); 
       $invoice[0].items[0]={"ID":this.person.ID,"other":value};
    }else{
      //here i do a "for" to create new invoice index, or new item 
         ....
       }
}

我想要的结果是这样的

Invoice{
      0:{ items{             
              0:{ ID:"123",other:"xxx"}
              1:{ ID:"234",other:"xxx"}
              2:{ ID:"233",other:"xxx"}
             }
         }
      1:{ items{             
              0:{ ID:"1323",other:"yyy"}
              1:{ ID:"1323",other:"xyyxx"}
              2:{ ID:"1213",other:"yyyy"}
             }
         }
      2:{ items{             
              0:{ ID:"12323",other:"zz"}
              1:{ ID:"1223",other:"zz"}
              2:{ ID:"1123",other:"zz"}
             }
         }
}
但是我只能做一个对象,

我不能调用推送事件,这是因为是一个对象,而不是一个数组,所以也许我需要做一些类似的事情 $invoice[0].items[0].push({"ID":this.person.ID,"other":value});请帮助我

我不完全理解您在这里使用的逻辑,但基本上您应该使用 push() 将新项目添加到数组中,而不是数字索引。items属性也应该是一个数组,而不是一个对象:

var $boletos = [];
function onclick(value){
    if($boletos.length === 0 || shouldStartANewInvoice) {
        $boletos.push({ items: [] }); 
    }
    $boletos[$boletos.length - 1].items.push({
        ID: this.person.ID,
        other:value
    });
}

只是为了给@JLRishe的答案添加上下文和示例。

实际上有两种方法可以做到这一点,具体取决于您的发票用例。例如,如果我在 C# 中提交服务器端,我会将其构造得更像一个对象 。否则,数组方法工作得很好 。

  1. 正如他建议的那样,Items是一个数组:http://jsfiddle.net/nv76sd9s/1/

  2. 另一种方法是让 Items 成为对象,其中 ID 作为键,值作为值:http://jsfiddle.net/nv76sd9s/3/

这里的区别在于最终对象的结构以及您计划如何使用它。在我的#2链接中,对象更加结构化。它还会影响循环访问它们的方式。例:

    var items = Invoice.Items;
    for (k in items) {
        var item = items[k];
        for (k in item) {
            console.log(k +': '+item[k]);
        }
    }