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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24353095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:37:23  来源:igfitidea点击:

Creating a array of objects using a constructor

javascriptarraysobject

提问by Ray Brennan

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

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

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

采纳答案by Mark Lavrynenko

Try this, JsBin sourses

试试这个,JsBin 发源地

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

回答by Krzysztof Safjanowski

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

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

回答by maxmeffert

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.

这是使用原型的另一种方法。类(如在 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);

}());

回答by Indranil Mondal

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

回答by Bharath

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

回答by plalx

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

您可以使用new,但您必须将它与构造函数一起使用(任何函数都可以用作构造函数)。该new操作者不能被应用到对象的文字。

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.

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

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

p.age; //0

回答by Akhlesh

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

JsFiddle 演示

回答by Harpreet Singh

Class in JS

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)