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

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

最佳答案

试试这个,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);

关于javascript - 使用构造函数创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24353095/

相关文章:

ios - 发送到不可变对象(immutable对象)的快速变异方法

java - 将包装类拆箱到 var-arg

JavaScript 和 React-native : How to properly move part of a component into a new class?

javascript - 加载状态永远不会变为真??(React - Redux)

javascript - 如何在隐藏输入字段(类型 ="text")上使用 jQuery.autocomplete ?

java - Retrofit2 将数组作为 HashMap 发送会产生不同的格式

javascript - FullCalendar 对象无法理解对象数组参数

javascript - JavaScript 的 Object.prototype 行为是什么?

javascript - 如何更改工具提示的样式/CSS?

javascript - Vue.js 组件在 jsp 文件中不起作用