如何在我的person对象构造函数中打印出所有人?

时间:2015-01-20 18:02:23

标签: javascript jquery html css

function person(a,b,c) {
 this.firstName = a;
 this.lastName = b;
 this.age = c;
};

var friend = new person("John", "Doe", 25);
var friend2 = new person ("Java", "Script", 20);
var friend3 = new person ("Mike", "Johnson", 26);

基本上我想要做的是创建一个用户输入他们的名字,姓氏和年龄的数据库。然后我想在屏幕上打印出每个用户的信息。如何打印出所有信息?我尝试过:for(var prop in person) {document.write(person[prop]); };但这似乎不起作用。请帮忙,这里有极端的新手。谢谢。

4 个答案:

答案 0 :(得分:1)

您可以将person个对象放在users列表中,如下所示:

var users = [];
users.push(friend, code);
users.forEach(function(pers) {
    for(var prop in pers) {
        console.log(pers[prop]); 
    };
 });

答案 1 :(得分:1)

// create an array to contain all the people
var people = [];

// push new people into the array
people.push(new person("John", "Doe", 25));
people.push(new person("Java", "Script", 20));

// create an array to contain our html
var html = [];

// loop over the array of people and add each person's
// information to the html you want to output
for (var i = 0, l = people.length; i < l; i++) {
    var person = people[i];
    for (var p in person) {
        html.push(person[p], '<br/>');
    }
    html.push('<br>');
}

// Add the completed html (using join) to the page
document.getElementById('output').innerHTML = html.join('');

DEMO

答案 2 :(得分:0)

function person(a,b,c) {
 this.firstName = a;
 this.lastName = b;
 this.age = c;

 this.print = function()
 {
    document.write(this.firstName);
    document.write(this.lastName);
    document.write(this.age);
  }
};

var friend = new person("John", "Doe", 25);
 friend.print();

答案 3 :(得分:0)

您正在使用&#34; person&#34;作为一个班级在这里。它(人)没有引用使用它创建的所有对象实例。您需要在某处存储这些实例的引用以打印它的列表。以下是如何做到这一点的粗略示例。

function person(a,b,c) {
 person.list = person.list || [];
 person.list.push(this)
 this.firstName = a;
 this.lastName = b;
 this.age = c;
};

var friend = new person("John", "Doe", 25);
var code = new person ("Java", "Script", 20);

for(i in person.list){
    var per = person.list[i];
    document.write("first name: "+per.firstname+" last name: "+per.lastname+ 
       " age: "+per.age);
}