【问题标题】:How add object to array jQuery如何将对象添加到数组jQuery
【发布时间】:2014-03-28 03:53:16
【问题描述】:

我正在尝试将我的对象添加到数组中,但完成后我拥有所有相同的对象

$('#Create').click(function(event) {
  event.preventDefault();

  var categoryId = $('#CatId').val();
  var enteredDate = $('#datepicker').val();
  var empId = $('#employeeID').text();
  var systemDate = $.datepicker.formatDate('dd.mm.yy', new Date());
  var obj = {
    CategoryId: categoryId,
    EnteredDate: enteredDate,
    SystemDate: systemDate,
    EmpId: empId
  };
  var arrToServer = [];
  var list = new Array();
  $("input[type=checkbox]:checked").each(function() {
    var productId = $(this).attr('id');
    obj.ProductId = productId;
    arrToServer.push(obj);                
  });
  arrToServer = JSON.stringify(arrToServer);
}

我的 arrToServer 有 2 个相同的对象,为什么?

【问题讨论】:

标签: jquery object each


【解决方案1】:

创建对象的副本,然后设置项目 ID。

$("input[type=checkbox]:checked").each(function () {
    var productId = $(this).attr('id');
    var clonedobj = jQuery.extend({}, obj); //create a shallow
    clonedobj.ProductId = productId;
    arrToServer.push(clonedobj);
});

【讨论】:

    【解决方案2】:

    我的 arrToServer 有 2 个相同的对象,为什么?

    因为您只是在循环之外创建 一个 对象,并将同一个对象多次推送到数组中。将对象传递给函数或将其分配给不同的变量不会创建对象的副本。

    在循环内部创建对象(循环是指.each 回调)。

    这是一个使用 .map 的示例,它更简洁 IMO:

    var arrToServer = $("input[type=checkbox]:checked").map(function() {
        return {
            CategoryId: categoryId,
            EnteredDate: enteredDate,
            SystemDate: systemDate,
            EmpId: empId,
            ProductId: $(this).attr('id')
        };
    }).get();
    

    【讨论】:

    • 您能解释一下为什么在您的示例末尾有一个 .get() 吗?
    • .get 返回一个数组。没有它,您将使用 jQuery 对象。
    • 啊,谢谢。当我搜索时,我看到这个引用了 Ajax:api.jquery.com/jquery.get。谢谢!
    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 2011-11-21
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多