这里的错误可能是什么。我需要将此firstName列表添加到
var text = '[' +
'{ "firstName" : "John", "lastName": "Doe"},' +
'{ "firstName" : "Ann", "lastName": "Smith"},' +
'{ "firstName" : "Peter", "lastName": "Jones"}]';
var arr = JSON.parse(text);
var list = function(employee) {
for (var i in employee.length) {
document.getElementById("demo").innerHTML += '<li>' + employee[i].firstName + '</li>';
}
};
list(arr);
&#13;
<ul id="demo"></ul>
&#13;
答案 0 :(得分:1)
您不应该使用for...in
来迭代数组。
这应该有用。
function list(employees) {
var html = '';
employees.forEach(function (employee) {
// Beware of XSS/HTML injection vulnerabilities here;
// the name is not sanitized and could contain HTML.
// Implementing sanitization is left as an exercise for the reader.
html += '<li>' + employee.firstName + '</li>';
});
// Only edit innerHTML once.
document.getElementById("demo").innerHTML += html;
};
list([ // Let's assume JSON.parse() has been called already.
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Ann', lastName: 'Smith' },
{ firstName: 'Peter', lastName: 'Jones' },
]);
答案 1 :(得分:0)
问题是你以错误的方式在循环中使用.. 看看documentation。它旨在迭代可数的对象属性。因此,您最好使用array.forEach代替
但在我的例子中,我还使用array.map函数将对象数组转换为字符串数组,将其连接成一个字符串并设置为目标节点的innerHTML。
我还在我的代码段中添加了关于使用+=
您的案例的评论。您可能会发现,在添加新值之前要清除列表,以便更好地将值赋予innerHTML
,因此使用array.map
构建列表内容可能是更好的选择。
const text = '[' +
'{ "firstName" : "John", "lastName": "Doe"},' +
'{ "firstName" : "Ann", "lastName": "Smith"},' +
'{ "firstName" : "Peter", "lastName": "Jones"}]';
const arr = JSON.parse(text);
// using aray.map()
const listNode = document.getElementById('demo')
function makeListItem(employee) {
return '<li>' + employee.firstName + '</li>'
}
function listEmployees(employees) {
listNode.innerHTML = employees.map(makeListItem).join('')
}
listEmployees(arr)
//using array.forEach()
const listNode2 = document.getElementById('demo2')
function listWithForEach (employees) {
employees.forEach(function(employee) {
listNode2.innerHTML += '<li>'+employee.firstName+'</li>'
})
}
//using += will append content to your list, so if you call your function twice, you'll get a repeating items.
listWithForEach(arr)
listWithForEach(arr)
<ul id="demo"></ul>
<ul id="demo2"></ul>