5 回答
TA贡献1828条经验 获得超6个赞
您可以尝试一个简单的 for 循环或 forEach 循环...
// json data
let data = {
"launches": [
{
"id": 2036,
"name": "Electron | Don't Stop Me Now",
"windowstart": "June 11, 2020 04:43:00 UTC",
"windowend": "June 11, 2020 06:32:00 UTC",
},
{
"id": 2037,
"name": "Don't Stop Me Now",
"windowstart": "June 11, 2020 04:43:00 UTC",
"windowend": "June 11, 2020 06:32:00 UTC",
}
]
};
// function for handling data manipulation
function printNames() {
let parsed = '';// temp variable for storing it as string
for (i = 0; i < data.launches.length; i++) { //iterate through each array item to fin require info
parsed += data.launches[i].id + ' ' + data.launches[i].name + "\n";
}
console.log(parsed)
let elem = document.getElementById('container');
elem.innerHTML = parsed; //Append it to container
}
printNames();
TA贡献1872条经验 获得超3个赞
var my_object = {
"launches": [
{
"id": 2036,
"name": "Electron | Don't Stop Me Now",
"windowstart": "June 11, 2020 04:43:00 UTC",
"windowend": "June 11, 2020 06:32:00 UTC",
}]};
for(var i=0; i<my_object.launches.length;i++){
console.log(my_object.launches[i].name);
}
TA贡献1770条经验 获得超3个赞
这就是循环访问对象数组并打印对象特定值的方式
jsonObj.launches.forEach(item => console.log(item.name))
TA贡献1862条经验 获得超7个赞
这是执行您建议的简单方法。
(我不确定你说的“打印...在 HTML 中“,所以我只是将每个字符串添加到 HTML 代码中的现有列表中。name
// An array that might be a JSON response from an HTTP request
const players = [
{ name: "Chris", score: 20, winner: false },
{ name: "Anne", score: 22, winner: true },
{ name: "Taylor", score: 14, winner: false }
];
// You can loop through an array with `for...of`
for(let player of players){
// You can access a property of "player" with `player.whateverThePropIsCalled`
addListItem(player.name);
}
// You can do whatever you want with the name, such as appending it to a list
function addListItem(name){
const textNode = document.createTextNode(name);
const listItem = document.createElement("LI");
listItem.appendChild(textNode);
const list = document.getElementById("list");
list.appendChild(listItem);
}
<ol id="list"></ol>
TA贡献1828条经验 获得超4个赞
如果您使用的是普通脚本。你可以做这样的事情。
var data = [{
"launches": [
{
"id": 2036,
"name": "Electron | Don't Stop Me Now",
"windowstart": "June 11, 2020 04:43:00 UTC",
"windowend": "June 11, 2020 06:32:00 UTC",
}]
}];
var names = data.map(i=>i.name);
names.forEach(i=>{
var div = document.createElement('div');
div.innerText = i;
document.body.appendChild(div);
})
添加回答
举报