Making an object in an array


#1

How can I make an Object in an array

Replace this line with your code.

`


#2

First make a constructor:

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

Then make a array and add items to it like so:

var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

I hope this helped :slight_smile:


#3

can you explain more?


#4

please show an example


#5

So this is an example of a function (constructor). I am giving the function a name of Person. This is the key to how I am putting objects into an array.

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

Here I am making a new array and naming it family.

var family = new Array();

Here I am adding objects to the new array I just made by using the constructor I wrote at the top.

family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

Does that make sense?


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.