javascript - Creating a array of objects using a constructor -
javascript - Creating a array of objects using a constructor -
i want have people array containing person objects can access fields in object array index.
normally i'd have gone , object collection or list etc.
can help me create work?...
var people = []; var person = { firstname:"john", age:50 }; function newperson(){ var p = new person(); //<<< #1. approach in js? p.firstname = "fred"; p.age = 21; people.push(p); } function totalage(){ var totalage =0; (i = 0; < people.length; i++){ totalage += people[i].age; //<<<<< #2. kind of access want. } }
try this, jsbin sourses
var people = []; function person(name, age){ // function constructor this.name = name; // not forget 'this.' this.age = age; } function addperson(name,age){ var p = new person(name,age); // here create instance people.push(p); } addperson("petia", 80); addperson("vasia", 20); function totalage(){ var total = 0; // not name local variables same function var i; // utilize var variable, otherwise global variable (i = 0; < people.length; i++){ total += people[i].age; } homecoming total; } var total = totalage(); console.log(total);
javascript arrays object
Comments
Post a Comment