我想知道将多个值分配给同一数据结构的5个不同实例的最佳/有效方法是什么(所有数据结构都相同)。
我的数据结构:
export class WeatherData {
date: string;
city: string;
country: string;
temperature: number;
minTemperature: number;
maxTemperature: number;
weather: any;
weatherIcon: any;
}
例如,我的minTemperature值目前是一个数字数组,长度为5,包含每天的最低温度。换句话说,数据结构的每个实例代表一天。
我有办法将该数组的第i个元素分配给第i个数据结构的minTemperature吗?这也必须在数据结构的其他字段(日期,城市,国家,......)
中完成答案 0 :(得分:0)
我会给你两个答案,因为直觉告诉我你在这种情况下可能更适合使用界面:
使用给定的类:
export class WeatherData {
date: string;
city: string;
country: string;
temperature: number;
minTemperature: number;
maxTemperature: number;
weather: any;
weatherIcon: any;
// set up a constructor:
constructor(props?: Partial<WeatherData>) {
// take an optional object containing properties of weather data and assign it
Object.assign(this, props);
}
}
// Setup for clarity sake
const temperatures[] = //....
const countries[] = //....
// more arrays as given...
let weatherDataObjects: WeatherData[] = [];
// Assuming these arrays are all the same length:
for (let i = 0; i < temperatures.length; i++) {
weatherDataObjects.push(new WeatherData({
temperature: temperatures[i],
country: countries[i],
// ... assign the rest
}));
}
但是,如前所述,如果您不打算在WeatherData类中使用任何成员方法,则接口可能更适合您 - 实质上是受约束的类型检查对象。 使用界面:
interface WeatherData {
date: string;
city: string;
country: string;
temperature: number;
minTemperature: number;
maxTemperature: number;
weather: any;
weatherIcon: any;
}
// Setup for clarity sake
const temperatures[] = //....
const countries[] = //....
// more arrays as given...
let weatherDataObjects: WeatherData[] = [];
// Assuming these arrays are all the same length:
for (let i = 0; i < temperatures.length; i++) {
weatherDataObjects.push({
temperature: temperatures[i],
country: countries[i],
// ... assign the rest
});
}