[英]After pushing objects into array, every object in the array has the same value
我對此功能有疑問。 當我將對象推入數組中時可以,但是當我檢索存儲的對象時,我在每個對象中都有相同的值。
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);
}
您需要在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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.