我绝不是javascript方面的专家,我正在努力学习。
我已经创建了一段简单的代码,它添加了一个person对象,并使用一些格式糟糕的字符串以HTML形式显示它。因为我有两个人(p1和p2),所以我希望将它们都添加到div“输出”中。这样做的目的是创建每个person对象的列表,并将属性放置在列表项中。
我的问题是-如何通过迭代来显示每个人的对象?
谢谢
<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>发布于 2014-11-05 11:10:08
你可以这样做。
我们用返回数据的html表示的方法来扩展person。每个新创建的person都可以使用它,这样p1和p2都可以使用它。我们使用p1.birthdate()和p2.birthdate()手动输出数据。但是,如果我们需要处理许多persons,我们希望将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>
发布于 2014-11-05 11:01:50
只需制作一个人员数组,然后遍历该数组。试着做这样的事情:
var persons = [
new person("John", "Dhoe", 22, new Date("December 13, 1973 11:13:00").toLocaleDateString()),
new person("Mr", "Andersson", 56, new Date("October 14, 1968 11:13:00").toLocaleDateString())
]; // An array of persons...
var html = '';
for(var i = 0; i < persons.length; i++){ // Iterate over all persons
html += persons[i].birthdate(); // And add the HTML for each person to `html`
}
output.innerHTML = html; // Finally, add the persons html to the output.发布于 2014-11-05 11:06:17
将birthdate函数放入person函数中。然后将所有人员放入一个数组中,并为每个人调用函数。
for (var i= 0; i< people.length; i++){
var output = document.getElementById("output");
output.innerHTML = output.innerHTML + people[i].birthdate();
}http://jsfiddle.net/v9katu8z/
https://stackoverflow.com/questions/26755476
复制相似问题