我正在尝试从联系人数组创建一个无序列表。
该数组类似于:
let contacts = [{firstName:"John", lastName:"Doe", age:46}, {firstName:"Mike", lastName:"Smith", age:46}, {firstName:"Joe", lastName:"Dirt", age:46}];
我可以从基本数组创建一个列表,如下所示:
var options = [
set0 = ['Option 1','Option 2'],
];
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));
我不太明白如何使用该对象创建列表。
最佳答案
在 JavaScript 中,对象可以通过使用 .或[]。
例如) array[i].firstName
或 array[i]['firstName']
您可以使用模板字符串或 JSON.stringify
const item = array[i];
item.appendChild(document.createTextNode(`firstName: ${item.firstName}, lastName: ${item.lastName}`));
或
item.appendChild(document.createTextNode(JSON.stringify(array[i]));
关于javascript - 如何迭代对象数组并将结果显示在列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56487315/