2

I want to have an People array containing Person objects so that I can access the fields in the object from the array index.

Normally I'd have gone with and object collection or List etc.

Can you help me make this work?...

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.
    }
}
1
  • 1
    Constructors need to be functions, not objects. Your "person" variable is initialized to a plain object, so you can't call it as a constructor. Commented Jun 22, 2014 at 16:12

8 Answers 8

2

Try this, 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);
Sign up to request clarification or add additional context in comments.

Comments

1

Little more objective

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());

Source: http://jsfiddle.net/Zkc43/3/ – thanks to @Akhlesh

Comments

1

here is another approach using prototypes. Classes (like in Java) are a fairly foreign concept to JavaScript, so i'd recommend not to try emulating them.

(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);

}());

Comments

0

Do something like this,

 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.
     }
}

Comments

0

You can use new, but you will have to use it with a constructor function (any function could be used as a constructor). The new operator cannot be applied to an object literal.

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

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

p.age; //21

If you want to use an object as a prototype for another object you can use Object.create.

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

p.age; //0

Comments

0

You can use constructor function for creating object like:-

 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

Comments

0

Class in 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)

3 Comments

Hi. Why did you use "this.createNewPerson"? (and thanks btw)
just an example function. I thought it would help you better understand. actually I used it as a constructor.
If every thing is clear(I hope), then you can accept any answer you liked most.
0

Try the following:-

       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;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.