oneiros
oneiros

Reputation: 3568

Populating an array of objects in javascript

Let us say I have an object Airport with members airportCode and airportCity like this:

function Airport(airportCode, airportCity) {
        this.airportCode = airportCode;
        this.airportCity = airportCity;
    };     

How can I create an array of objects Airport to which I can add. In Java, this would work like this:

while(st.hasMoreTokens()) {
    Airport a = new Airport();
    a.airportCode = st.nextToken();
    a.airportCity = st.nextToken();
    airports.add(a);
}

Upvotes: 5

Views: 19356

Answers (3)

user1073456
user1073456

Reputation:

A very short answer:

airports.push(new Airport("code","city"));

Upvotes: 11

Esailija
Esailija

Reputation: 140210

It's not really that different

var airports = [];
while (st.hasMoreTokens()) {
    var a = new Airport();
    a.airportCode = st.nextToken();
    a.airportCity = st.nextToken();
    airports.push(a);
}

Upvotes: 4

Chandu
Chandu

Reputation: 82893

Try this:

function Airport(airportCode, airportCity) {
        this.airportCode = airportCode;
        this.airportCity = airportCity;
};

var dataArray = [];

for(var i=0; i< 10; i++){
    dataArray[i] = new Airport("Code-" + i, "City" + i);
}

Upvotes: 7

Related Questions