Typescript在类中创建数组然后推送到数组

时间:2017-08-25 16:12:34

标签: arrays class typescript

我想把一些艺术品放入阵列数组中。每件艺术品都有我试图用类描述的属性。我想用类创建类型并将数据推送到数组。我不确定构造函数是做什么的?我认为它应该提供一种创建类的新实例的方法吗?

我的ts代码如下:

class Artwork {
    private _artTitle: string;
    private _slideUrl: string;
    private _artPrice: string; 
    private _artMedium: string; 
    private _artDimensions: string; 
    private _artDesc: string;


  constructor(
        artTitle: string,
        slideUrl: string,
        artPrice: string,
        artMedium: string,
        artDimensions: string,
        artDesc: string
    ){

    this._artTitle = artTitle;
    this._slideUrl = slideUrl;
    this._artPrice = artPrice;
    this._artMedium = artMedium;
    this._artDimensions = artDimensions;
    this._artDesc = artDesc;

    }

  }

    let Artwks: string [];

    Artwks.push(new Artwork());

    Artwks[0].slideUrl = './assets/SBI_Slide_1.jpg';
    Artwks[0].artTitle = "'Surprising Breakfast Ideas'";
    Artwks[0].artPrice = "£400";
    Artwks[0].artMedium = "Acrylic on canvas";
    Artwks[0].artDimensions = '7" x 12"';
    Artwks[0].artDesc = '...Inspired by trailing clauses and footling concerns, this latest injunction into the darkened forest of prevarication yields a miasma of plethoras, tantalising us with a fleeting array of nuances...';



    console.log(Artwks);

3 个答案:

答案 0 :(得分:1)

以下代码应该有效:

 let artworks: Artwks[] = [];

 artworks.push(new Artwork(
 "'Surprising Breakfast Ideas'",
 './assets/SBI_Slide_1.jpg',
 "£400",
 "Acrylic on canvas",
 '7" x 12"',
  '...Inspired by trailing clauses and footling concerns, this latest injunction into the darkened forest of prevarication yields a miasma of plethoras, tantalising us with a fleeting array of nuances...';
 ));

您必须填写构造函数中的所有参数以创建类的新实例

答案 1 :(得分:1)

你需要声明变量并调用类的构造函数,如下所示:

   let Artwks: Artwork []=[];

    Artwks.push(new Artwork("'Surprising Breakfast Ideas'", '', '', '', '', ''));

但是如果你的类只有数据,我建议把它作为一个接口并使用json文字来创建数组元素:

interface Artwork {

    artTitle: string;
    slideUrl?: string; //optional memeber 
    artPrice: string;
    artMedium?: string;
    artDimensions?: string;
    artDesc?: string
}

let Artwks: Artwork []=[];

Artwks.push({
    artTitle: '',
    artPrice: '',
    artDesc: '',
    artDimensions:''
});

此版本更具可读性,并且可以更轻松地制作某些成员可选

答案 2 :(得分:0)

您可以将参数传递给构造函数,以使用您指定的属性创建新实例,如下所示:

在将Artwork对象推送到它之前,您还需要启动新的空数组。

let Artwks:Array<Artwork>=[];

let artwk = new Artwork("'Surprising Breakfast Ideas'",'./assets/SBI_Slide_1.jpg', "£400", "Acrylic on canvas", '7" x 12"', '...Inspired by trailing clauses and footling concerns, this latest injunction into the darkened forest of prevarication yields a miasma of plethoras, tantalising us with a fleeting array of nuances...');

Artwks.push(artwk);

console.log(Artwks);