gpt4 book ai didi

javascript - 将推送的元素拆分为 Javascript 空数组

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

我有一个名为 result[] 的空数组。然后用户单击一个链接,该链接调用一个名为 getId() 的函数,该函数传递点击的 ID 以检查它是否与另一个名为 productsArray[] 的数组中的 ID 匹配。

<a href="javascript:void(0)" class="abc" onClick="getId(this.id)">Jackets</a>

var productsArray = [
{id:0, title:"Product A",description:"description 0"},
{id:0, title:"Product B",description:"description 1"},
{id:2, title:"Product C",description:"description 2",},
{id:0, title:"Product D",description:"description 3",},
{id:4, title:"Product A",description:"description 4",},
{id:5, title:"Product A",description:"description 5",}
],
result = [];

如果用户单击 Jackets 链接(其 ID 为 0),将返回 productsArray 中的 3 个项目:产品 A、B 和 D。

我必须实现的代码确实有效:

var output;
var container;

for(key in productsArray) {

if (productsArray[key].id == id) {
result.push(productsArray[key].title, productsArray[key].description);
}
}

container = document.getElementById('content');
output=result;
container.innerHTML=output;

<div id="content"></div>

但问题是所有数据都分配给了 result[] 键索引:

例如:

[0]Produduct A title
[1]Product B title
[2]Product C title

我想实现一种按照以下方式拆分数据的方法:

output+= result[0].title + result[0].description

感谢任何帮助。

干杯

最佳答案

您可以映射结果和产品的所需键。

function getId(id) {
document.getElementById('content').innerHTML = productsArray
.filter(function (product) {
return product.id == id;
})
.map(function (product) {
return ['title', 'description']
.map(function (key) { return product[key]; })
.join(' ');
})
.join('<br>');
}

var productsArray = [{ id: 0, title: "Product A", description: "description 0" }, { id: 0, title: "Product B", description: "description 1" }, { id: 2, title: "Product C", description: "description 2" }, { id: 0, title: "Product D", description: "description 3" }, { id: 4, title: "Product A", description: "description 4" }, { id: 5, title: "Product A", description: "description 5" }];
<a href="javascript:void 0" onclick="getId(0)">Jackets</a>
<div id="content"></div>

关于javascript - 将推送的元素拆分为 Javascript 空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45212882/

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