将对象推入数组后,数组中的每个对象都具有相同的值

时间:2017-06-17 05:19:38

标签: javascript

我遇到了这个功能的问题。当我将对象推入数组时,没关系,但是当我检索存储的对象时,我在每个对象中都有相同的值。

function saveDetails() {
  var details = [];
  var productDetails = {};
  var id = $('#ddlDeliveryBoy option:selected').val();
  var count = $('#tbCustomer tbody tr').length;
  for (var index = 0; index < count; index++) {
    var tr = $('#tbCustomer tbody tr')[index];
    var countTD = $(tr).children('td').length - 4;
    for (var j = 3; j < (countTD + 4); j++) {
      var td = $(tr).children('td')[j];
      var txt = $(td).find('input[type="text"]');
      if ($.isNumeric(txt.val())) {
        productDetails.CustomerID = $(tr).data('id');
        productDetails.ProductID = $(td).data('id');
        productDetails.Quantity = parseFloat(txt.val()).toFixed(2);
        details.push(productDetails);
      }
    }
  }
  console.log(details);
}

1 个答案:

答案 0 :(得分:2)

你需要在if循环中移动 productDetails 初始化。 这是代码。

function saveDetails() {
  var details = [];
  var id = $('#ddlDeliveryBoy option:selected').val();
  var count = $('#tbCustomer tbody tr').length;
  for (var index = 0; index < count; index++) {
    var tr = $('#tbCustomer tbody tr')[index];
    var countTD = $(tr).children('td').length - 4;
    for (var j = 3; j < (countTD + 4); j++) {
      var td = $(tr).children('td')[j];
      var txt = $(td).find('input[type="text"]');
      if ($.isNumeric(txt.val())) {
        let productDetails = {};
        productDetails.CustomerID = $(tr).data('id');
        productDetails.ProductID = $(td).data('id');
        productDetails.Quantity = parseFloat(txt.val()).toFixed(2);
        details.push(productDetails);
      }
    }
  }
  console.log(details);
}