5

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);
}
2
  • 2
    Create an array using var airports = [];. Then, in the loop, create an Airport instance, and add it to the array using the airports.push method. Commented Jul 17, 2012 at 21:12
  • 2
    What is st in your javascript code? Commented Jul 17, 2012 at 21:15

3 Answers 3

11

A very short answer:

airports.push(new Airport("code","city"));
Sign up to request clarification or add additional context in comments.

Comments

7

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

3 Comments

Or simply dataArray.push(new Airport(...)); which is slightly faster. :-)
here's another jsperf.com/push-vs-index-2 To show that it's much easier to write as well.
I take back my previous comment since the results are not consistent across browsers/os.
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.