javascript 在javascript中填充对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11530944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:33:05 来源:igfitidea点击:
Populating an array of objects in javascript
提问by oneiros
Let us say I have an object Airport with members airportCode and airportCity like this:
假设我有一个对象 Airport ,其成员为 airportCode 和 airportCity ,如下所示:
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:
如何创建可以添加的对象 Airport 数组。在 Java 中,这会像这样工作:
while(st.hasMoreTokens()) {
Airport a = new Airport();
a.airportCode = st.nextToken();
a.airportCity = st.nextToken();
airports.add(a);
}
回答by
A very short answer:
一个非常简短的答案:
airports.push(new Airport("code","city"));
回答by Chandu
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);
}
回答by Esailija
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);
}