gpt4 book ai didi

javascript - 将对象推送到数组中只返回最后推送的对象

转载 作者:行者123 更新时间:2023-11-30 08:42:14 25 4
gpt4 key购买 nike

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

<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 中推送的最后一个对象。请告诉我为什么它不显示所有三个对象。此代码的结果表是

id      name    price

ga3 gadget3 $8.99

最佳答案

不确定这是否相关,但如果人们仍然来这里寻找简单的解决方案......

只需将对象字符串化并再次进行 JSON.parse 以复制它,而不是像这样引用对象;

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

关于javascript - 将对象推送到数组中只返回最后推送的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25321777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com