简体   繁体   English

在数组中推送对象仅返回推送的最后一个对象

[英]Pushing objects in an array only returns last object pushed

I am working on YUI DataTables, to populate the data table i want to send the columns and their values dynamically from outside, for that i have written the following code: 我正在研究YUI DataTables,以填充数据表我想从外部动态发送列及其值,因为我已经编写了以下代码:

<html>
<script src="http://yui.yahooapis.com/3.17.2/build/yui/yui-min.js"></script>
<div class="example yui3-skin-sam" id="simple"> <!-- You need this skin class -->
</div>

<script>
var cols = ["id", "name", "price"];
var obj = {
    id: "",
    name: "",
    price: ""
};
var data2 = new Array();
obj.id = "ga";
obj.name = "gadget";
obj.price = "$6.99";
data2.push(obj);
obj.id = "ga2";
obj.name = "gadget2";
obj.price = "$7.99";
data2.push(obj);
obj.id = "ga3";
obj.name = "gadget3";
obj.price = "$8.99";
data2.push(obj);
YUI().use("datatable", function (Y) {
    // A table from data with keys that work fine as column names
    var simple = new Y.DataTable({
        columns: cols,
        data   : data2,
        summary: "Price sheet for inventory parts",
        caption: "Example table with simple columns"
    });

    simple.render("#simple");

});
</script>
</html>

now the problem is that, it shows only the last obj pushed in data2.. kindly tell me why its not displaying all three objs. 现在的问题是,它只显示数据2中推送的最后一个obj ..请告诉我为什么它不显示所有三个objs。 the resulting table from this code is 此代码生成的表是

id      name    price

ga3   gadget3   $8.99

it will give all array values 它将提供所有数组值

function obj(id, name, price) {
     this.id = id;
     this.name = name;
     this.price = price;
 }

 var array = new Array();

 var point = new obj("ga", "gadget", "$6.99");

 array.push(point);

 var point = new obj("ga2", "gadget2", "$7.9");

 array.push(point);

Both answers above ( 2480125 , 2480125 ) will work, but they require that you manually input the new object's properties for every new object added to the array. 以上(这两个答案24801252480125 )会的工作,但他们需要你手动输入新对象的为每一位新对象属性添加到阵列中。

You can avoid that inflexibility with a for..in loop ( docs ): 您可以使用for..in循环( docs )避免这种不灵活性:

var newObj = function(object) {
  var newObject = {};
  for (var key in object) {
    if (object.hasOwnProperty(key)) {
      newObject[key] = object[key];
    }
  }
  return newObject;
};

var obj = {
  id: 'foo',
  name: 'gadget',
  price: '$6.99'
};

data2 = [];

data2.push( newObj(obj) );

obj.id = 'bar';
obj.name = 'baz';
obj.price = '$4.44';

data2.push( newObj(obj) );

console.log(data2);
data2.forEach(function(item){
  console.log("%s, %s, %s", item.id, item.name, item.price);
});
// data2 now contains two distinct objects, rather than one object reference added to the array twice.

JSFiddle for above code JSFiddle上面的代码

Objects are reference objects. Objects是引用对象。

obj.id = "ga";
obj.name = "gadget";
obj.price = "$6.99";
data2.push(obj);

obj.id = "ga2";
obj.name = "gadget2";
obj.price = "$7.99";
data2.push(obj);

This means that when you update the obj the second time, you're actually updating all references to that object. 这意味着当您第二次更新obj时,您实际上正在更新对该对象的所有引用。

If you examine your data2 array you'll see that it has 3 elements and that all elements are the same. 如果检查data2数组,您将看到它有3个元素,并且所有元素都相同。

try updating your code to something like this 尝试将代码更新为这样的代码

data2.push({
    id : "ga",
    name : "gadget",
    price : "$6.99"
});
data2.push{(
    id : "ga2",
    name : "gadget2",
    price : "$7.99"
)};
data2.push({
    id : "ga3",
    name : "gadget3",
    price : "$8.99"
});

None of these answers worked for me, and I can't explain why it worked, but adding a character value to the element I was pushing inline was the only way I could get it to work properly. 这些答案都没有对我有用,我无法解释它为什么有用,但是为我内联的元素添加一个字符值是我能让它正常工作的唯一方法。 I tried the suggestions of creating new objects or even just creating new variables and pushing either the new object or new variables but to no avail, it just kept rewriting each element of the array whenever it would push a new element such that the entire array would be the final value of the loop each time. 我尝试了创建新对象的建议,甚至只是创建新变量并推送新对象或新变量但无济于事,它只是在推动一个新元素时重写数组的每个元素,这样整个数组就会每次都是循环的最终值。 So in the end this is what I had to do to get it to work: 所以最后这是我必须做的才能让它发挥作用:

var returnArray = [];
while(...){
    returnArray.push('' + obj.value);
}

Not sure if this is relevant anymore but if people still come here looking for an easy solution... 不确定这是否相关,但如果有人仍然来这里寻找一个简单的解决方案......

Just stringify the object and JSON.parse it again to copy it instead of referencing the object like so; 只需对对象进行字符串化并再次对其进行JSON.parse复制,而不是像这样引用对象;

data2.push(JSON.parse(JSON.stringify(obj)));

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

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