我绝不是 javascript 方面的专家,并且正在努力学习。
我创建了一段简单的代码,用于添加一个 person 对象并以 HTML 格式显示它,其中包含一些格式不正确的字符串。由于我有两个人(p1 和 p2),我希望将他们都添加到 div“输出”中。这个想法是创建每个人员对象的列表并将属性放置在列表项中。
我的问题是 - 如何通过迭代显示每个人对象?
谢谢
<body>
<div id="output"></div>
<script>
function person (fname, lname, age, birth)
{
this.firstname = fname;
this.lastname = lname;
this.age = age;
this.birth = birth;
}
var p1 = new person("John", "Dhoe", 22, new Date("December 13, 1973 11:13:00").toLocaleDateString());
var p2 = new person("Mr", "Andersson", 56, new Date("October 14, 1968 11:13:00").toLocaleDateString());
p1.birthdate = function () {
return "<ul>" +
"<li>" + "<b>Name: </b>" + this.firstname + " " + this.lastname + "</li>" +
"<li>" + "<b>Age: </b>" + this.age + "</li>" +
"<li>"+ "<b>Birthdate: </b>" + this.birth + "</li>" +
"</ul>";
}
output.innerHTML = p1.birthdate();
</script>
</body>
最佳答案
好吧,你可以这样做。
我们使用返回数据 html 表示的方法扩展 person
。它可供每个新创建的 person
使用,因此 p1
和 p2
都可以使用它。
我们使用 p1.birthdate()
和 p2.birthdate()
手动输出数据。但是,如果我们需要处理许多 person
,我们希望将 persons
存储到某个数组中,然后迭代它。
var persons = [];
function person (fname, lname, age, birth) {
this.firstname = fname;
this.lastname = lname;
this.age = age;
this.birth = birth;
}
person.prototype.birthdate = function () {
var html = '';
html += "<ul>" +
"<li>" + "<b>Name: </b>" + this.firstname + " " + this.lastname + "</li>" +
"<li>" + "<b>Age: </b>" + this.age + "</li>" +
"<li>"+ "<b>Birthdate: </b>" + this.birth + "</li>" +
"</ul>";
return html;
}
persons.push(new person("John", "Dhoe", 22, new Date("December 13, 1973 11:13:00").toLocaleDateString()));
persons.push(new person("Mr", "Andersson", 56, new Date("October 14, 1968 11:13:00").toLocaleDateString()));
var output = document.getElementById('output');
for (var i = 0; i < persons.length; i++) {
output.innerHTML += persons[i].birthdate();
}
<div id="output"></div>
关于javascript - 遍历对象 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26755476/