使用构造函数创建对象数组

时间:2014-06-22 16:09:29

标签: javascript arrays object

我希望有一个包含Person对象的People数组,以便我可以从数组索引访问对象中的字段。

通常我已经和对象集合或列表等一起去了。

你能帮我做这个吗?...

var people = [];

var person = {
    firstName:"John",
    age:50
  };



function newPerson(){       
    var p = new person();   //<<< #1. Is this a good approach in JS?
    p.firstName = "Fred";
    p.age = 21;

    people.push(p);
}


function totalAge(){

    var totalAge =0; 
    for (i = 0; i < people.length; i++){
        totalAge += people[i].age;   //<<<<< #2. This is the kind of access I want.
    }
}

8 个答案:

答案 0 :(得分:2)

试试这个,JsBin sourses

    var people = [];

    function Person(name, age){  // Function constructor
      this.name = name;          // do not forget 'this.'
      this.age = age;
    }

    function addPerson(name,age){    
        var p = new Person(name,age); // here we create instance
        people.push(p);
    }

    addPerson("Petia", 80);
    addPerson("Vasia", 20);


    function totalAge(){
        var total = 0;      // do not name local variables same as function
        var i;             // use var for i variable, otherwise it would be global variable 
        for (i = 0; i < people.length; i++){
            total += people[i].age; 
        }
        return total;
    }

    var total = totalAge();
    console.log(total);

答案 1 :(得分:1)

更客观一点

function People() {
    this.people = [];
}

People.prototype.getTotalAge = function() {
   return this.people.reduce(function(totalAge, person) {
        return totalAge + person.age;
    }, 0); 
};

People.prototype.add = function() {
    var people = Array.prototype.slice.call(arguments);
    this.people = this.people.concat(people);
};

//Person function behave as a class by this you can make new instance
function Person(fname, age) {
    this.firstName = fname;
    this.age = age;
}

var people = new People();
var p1 = new Person("fred", 21);
var p2 = new Person("John", 24);
people.add(p1, p2);

alert(people.getTotalAge());

来源:http://jsfiddle.net/Zkc43/3/ - 感谢@Akhlesh

答案 2 :(得分:1)

这是使用原型的另一种方法。 类(如Java中)对JavaScript来说是一个相当陌生的概念,因此我建议不要尝试模拟它们。

(function(){

    var people, Person, totalAge;

    // a Person prototype
    Person = Object.create({});

    // factory method creating Person objects
    Person.create = function Person_create (firstName, age) {

        var p = Object.create(Person);

        p._firstName = firstName;
        p._age = age;

        return p;

    };

    // getter for _age
    Person.getAge = function Person_getAge () {

        return this._age;

    };

    // generate some test values
    function populate (max) {

        var result, i;

        result = [];
        i = 0;

        while (i < max) {

            result.push(Person.create("Person"+i,i));
            i++;

        }


        return result;

    }

    // array containing test objects
    people = populate(100);

    // compute the sum of all Person.age
    totalAge = people.reduce(function(age,p){

        return age + p.getAge();

    }, 0); // <- 0 as initial value, basically you choose the neutral element for the operation in the given group (for multiplication initial value would be 1)

    console.log(totalAge);

}());

答案 3 :(得分:0)

做这样的事,

 var people = [];

function newPerson(){

    people.push({"firstName":"Fred", "age":21});
}


function totalAge(){

    var totalAge =0; 
    for (i = 0; i < people.length; i++){
          totalAge += people[i].age;   //<<<<< #2. This is the kind of access I want.
     }
}

答案 4 :(得分:0)

您可以使用new,但必须使用构造函数(任何函数都可以用作构造函数)。 new运算符无法应用于对象文字。

function Person(firstName, age) {
    this.firstName = firstName;
    this.age = age;
}

var p = new Person('Fred', 21);

p.age; //21

如果您想将对象用作另一个对象的原型,可以使用Object.create

var basePerson = { name: 'Default', age: 0 },
    p = Object.create(basePerson);

p.age; //0

答案 5 :(得分:0)

您可以使用构造函数来创建对象,如: -

 var people = [];
 //Person function behave as a class by this you can make new instance
 function Person(fname, age) {
    this.firstName = fname;
    this.age = age;
 }

 var p1 = new Person("fred", 21);
 var p2 = new Person("Jhon", 24);
 people.push(p1, p2);


 function totalAge() {

   var totalAge = 0;
   for (i = 0; i < people.length; i++) {
      totalAge += people[i].age; //<<<<< #2. This is the kind of access I want.
   }
   return totalAge;
 }

JsFiddle Demo

答案 6 :(得分:0)

JS中的类

var Person = function(firstName, age) {
    this.firstName = '';
    this.age = '';
    this.createNewPerson=function(firstName, age) {
        this.firstName = firstName;
        this.age = age
    }
    this.createNewPerson(firstName, age)
}

var people = [];
var newPerson = new Person('harp',23);
people.push(newPerson)

答案 7 :(得分:0)

请尝试以下方法: -

       function test(){
            var person = new Person('Jhon',10),
            person2 = new Person('Jhons',20),
            persons = [],total =0 ;
            persons.push(person);
            persons.push(person2);

            for(var i=0; i<persons.length; i++){
                total += persons[i].age;
            }
            console.log(persons,total);
        }
        function Person(name,age) {  
            this.name = name;
            this.age =age;
            return this;
        }