迭代对象 - Javascript

时间:2014-11-05 10:56:50

标签: javascript prototype

我绝不是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>

3 个答案:

答案 0 :(得分:1)

只需创建一个人数组,然后迭代该数组。尝试这样的事情:

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.

答案 1 :(得分:1)

嗯,你可以这样做。

我们使用返回数据的html表示的方法扩展person。它可用于创建的每个新person,因此p1p2都可以使用它。 我们使用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>

答案 2 :(得分:-1)

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/