推入数组中的对象仅返回最后推入的对象 [英] Pushing objects in an array only returns last object pushed

查看:213
本文介绍了推入数组中的对象仅返回最后推入的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用YUI DataTables,以填充我想从外部动态发送列及其值的数据表,为此,我编写了以下代码:

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:

<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>

现在的问题是,它仅显示data2中推送的最后一个obj.请告诉我为什么它不显示所有三个obj.此代码生成的表是

now the problem is that, it shows only the last obj pushed in data2.. kindly tell me why its not displaying all three objs. the resulting table from this code is

id      name    price

ga3   gadget3   $8.99

推荐答案

它将给出所有数组值

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);

这篇关于推入数组中的对象仅返回最后推入的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆