简体   繁体   English

Array.Push仅返回最后推送的对象。如何解决?

[英]Array.Push returns the last pushed object only..How to fix it?

I Know this question may be duplicate, but none of the other answers worked for me.. I am trying to send datatable valueS in an array to controller. 我知道这个问题可能是重复的,但是没有其他答案对我有用我正在尝试将数组中的数据表valueS发送给控制器。 but, array.push() returns the last object only. 但是, array.push()仅返回最后一个对象。

<script> 
  var dd = table.rows().data().toArray();
  var data1 = new Array();
  var CData= {};

 for (i = 0; i < dd.length; i++) {
  CData.Date = dd[i][1];
  CData.Description = dd[i][2];
  data1.push(CData);
}
 $.ajax({
type: "POST",
url: "/Test/Create",
contentType: "application/json;",
headers: { 'RequestVerificationToken': gettoken() },
data: JSON.stringify(data1:data1),
success: function () {
 alert('success');
},
error: function () {
   alert('failure');
}
 });
</script>

How to fix it? 如何解决?

It is because you are always modifying the same object and not creating a seperate one for every iteration of dd . 这是因为您总是在修改同一个对象,而不是为dd每次迭代创建单独的对象。

You should be creating a new one in the loop to avoid overwriting the same object each time : 您应该在循环中创建一个新对象,以避免每次都覆盖相同的对象:

 for (i = 0; i < dd.length; i++) {
  var CData= {}; // now new object each time
  CData.Date = dd[i][1];
  CData.Description = dd[i][2];
  data1.push(CData);
}

Directly do:- 直接做:

for (i = 0; i < dd.length; i++) {
  data1.push({
    Date: dd[i][1], 
    Description:  dd[i][2]
  });
}

Now these 3 line of code will be removed:- 现在,这三行代码将被删除:

var CData= {};

CData.Date = dd[i][1];
CData.Description = dd[i][2];

Try the following, it is not recommended to declare variables inside loops (unnecessary memory allocation). 请尝试以下操作,不建议在循环内声明变量(不必要的内存分配)。

var dd = table.rows().data().toArray();
var data1 = new Array();

for (i = 0; i < dd.length; i++) {
  data1.push({
    Date: dd[i][1],
    Description: dd[i][2]
  });
}

Here, CData is defined as Object. 在此,CData被定义为对象。 It takes only last values because it everytime overwriting and finally last values are storing. 它只需要最后一个值,因为它每次都覆盖并且最后一个最后值正在存储。 Instead of it, use array to store object values in it. 取而代之的是,使用数组在其中存储对象值。

Example : 范例

var dd = table.rows().data().toArray();
var data1 = new Array();
var CData= [];

for (i = 0; i < dd.length; i++) {
    CData[i] = {"Date" : dd[i][1],"Description" : dd[i][2]};
}
var required_data = JSON.stringify(CData);

finally send this(required_data) to ajax call. 最后发送这个(required_data)到ajax调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM