2017-12-28 15 views
0

동일한 데이터 구조 (모든 데이터 구조가 동일 함)의 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

변경되었습니다. 그것이 TypeScript 또는 JavaScript라면 아무런 차이가 없을 것이라고 생각했습니다. –

+0

5 가지 항목 각각에 대해'새로운 WeatherData()'를 원하십니까? – charlietfl

답변

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

+0

저는 타이프 스크립트 전문가는 아니지만 실제 인터페이스를 사용하는 것으로 보이지 않습니다. – charlietfl

+0

@charlietfl 좋은 잡기, 고정됨. 감사! –