2012-07-17 127 views
4

數組讓我們說我有一個對象機場,成員AIRPORTCODE和airportCity這樣的:填充對象在JavaScript

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

如何創建對象的數組機場,我可以補充。在Java中,這將這樣的工作:

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

創建一個使用'var airports = [];'的數組。然後,在循環中創建一個'Airport'實例,並使用['airports.push']將其添加到數組中(https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push ) 方法。 – 2012-07-17 21:12:47

+1

JavaScript代碼中的「st」是什麼? – Bergi 2012-07-17 21:15:03

回答

10

一個非常簡短的回答:

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

試試這個:

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

或簡單地'dataArray.push(新機場(...));'稍快。 :-) – YMMD 2012-07-17 21:22:23

+1

基於索引的訪問優於推動性能 – Chandu 2012-07-17 21:24:10

+2

不,「push()」更快。 ;)嘗試一下:http://jsperf.com/index-vs-push – YMMD 2012-07-17 21:25:41

4

這不是真的那麼不同

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