【问题标题】:Assign Multiple Values To Multiple Data Structures为多个数据结构分配多个值
【发布时间】:2017-12-28 20:36:26
【问题描述】:

我想知道将多个值分配给同一数据结构的 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?数据结构的其他字段也必须这样做(日期、城市、国家/地区……)

【问题讨论】:

  • 这对我来说就像打字稿。如果是,请编辑您的帖子以说明。
  • 已更改。认为如果它是 TypeScript 或 JavaScript 不会有任何区别。
  • 您是否想要这 5 项中的每一项都有一个 new WeatherData()
  • 是的,根据我的数组中的值,每个字段都有不同的值。

标签: javascript typescript data-structures


【解决方案1】:

我会给你两个答案,因为直觉告诉我,在这种情况下你可能更适合使用接口:

使用给定的类:

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

【讨论】:

  • 我不是打字大师,但您似乎没有使用实际界面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多