使用 javascript 中的对象默认值初始化数组

Initial an array with an object default value in javascript

我有以下 类,我想初始化 citiesRegistered,其中包含公园 'Times' 和 'Blues' 以及学校 'High' 和 middle 的城市对象的初始值但目前它是一个空对象

export const initialState: CustomerState = {
  customer: new Customer(),
};

export class Customer{
id: number;
age: number;
cars: carClass;
phoneNumbers: string[];
}

export class carClass{
name:string;
citiesRegistered:city[] = [];   //This is what makes it empty. How can I put default values of cities in here
}

export class city{
parks: string[] = ['Times','Blues'],
lakes: string[] = [],
schools: string[] = ['High','Middle']
}

我认为您可能需要稍微更改一下初始化值和默认值:

class Car {
    name: string = '';
    citiesRegistered: City = {
        lakes: ['MyLake'],
        parks: ['MyPark'],
        schools: ['MySchool']
    }
}

class Customer {
    id: number = 0;
    age: number = 0;
    car: Car = new Car();
    phoneNumbers: string[] = [];
}

const initialState = {
    customer: new Customer(),
};


class City {
    parks: string[] = ['Times', 'Blues']
    lakes: string[] = []
    schools: string[] = ['High', 'Middle']
}

console.log(initialState.customer.car.citiesRegistered)

输出

lakes: ["MyLake"]
parks: ["MyPark"]
schools: ["MySchool"]

Playground