我如何从数组中获取特定值用于循环
How can i get specific values from array use for in loop
你好,我有以下数组:
var data = [
{
title: "title 1",
data2: [
"content",
]
},
{
title: "title 1",
data2: [
"content",
]
}
];
如何在循环中获取标题和数据 2 值?
非常感谢。
编辑:
问题已经在猫@Niklas Higi 的帮助下解决了,但是,
如何在 .append 函数中获取我的 html 模板的值:
<div class="data">
<div class="data-item">
<h6>'+data.title+'</h6>
<ul>
<li>contents from data2 value</li>
</ul>
<div>
<div>
我需要为 li 标签获取 data2 值。
for(let item of data) {
console.log(item.title);
console.log(item.data2);
}
请注意,我使用的是 for of
而不是您标签建议的 for in
。 for in
迭代索引(如果是数组 0
、1
、...),而 for of
迭代项目(Object
在你的情况)。
对您编辑的回答: 在 for
循环中使用 document.createElement()
and add them to your .data
container using .appendChild()
创建您需要的元素。对于 <ul>
,您可以创建另一个 for of
循环来遍历列表项并将它们添加到您使用 document.createElement()
.
创建的 <ul>
标签中
// Iterate through array
data.forEach((item) => {
// Do stuff with items here,
// using dot-notation. We will
// just log them in this example.
console.log(item.title);
console.log(item.data2);
});
你好,我有以下数组:
var data = [
{
title: "title 1",
data2: [
"content",
]
},
{
title: "title 1",
data2: [
"content",
]
}
];
如何在循环中获取标题和数据 2 值?
非常感谢。
编辑:
问题已经在猫@Niklas Higi 的帮助下解决了,但是,
如何在 .append 函数中获取我的 html 模板的值:
<div class="data">
<div class="data-item">
<h6>'+data.title+'</h6>
<ul>
<li>contents from data2 value</li>
</ul>
<div>
<div>
我需要为 li 标签获取 data2 值。
for(let item of data) {
console.log(item.title);
console.log(item.data2);
}
请注意,我使用的是 for of
而不是您标签建议的 for in
。 for in
迭代索引(如果是数组 0
、1
、...),而 for of
迭代项目(Object
在你的情况)。
对您编辑的回答: 在 for
循环中使用 document.createElement()
and add them to your .data
container using .appendChild()
创建您需要的元素。对于 <ul>
,您可以创建另一个 for of
循环来遍历列表项并将它们添加到您使用 document.createElement()
.
<ul>
标签中
// Iterate through array
data.forEach((item) => {
// Do stuff with items here,
// using dot-notation. We will
// just log them in this example.
console.log(item.title);
console.log(item.data2);
});