typescript 初始化对象数组 - Angular

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49361760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:17:07  来源:igfitidea点击:

Initializing array of objects - Angular

arraysangulartypescriptobject

提问by Mario

I have an array of objects and when I try to access to it, I get an error saying:

我有一个对象数组,当我尝试访问它时,我收到一条错误消息:

TypeError: Cannot set property 'ID' of undefined

类型错误:无法设置未定义的属性“ID”

My code is the following:

我的代码如下:

export class Carimplements OnInit {
  pieces: Piece[] = [];

  test(pos){
    this.pieces[pos].ID = "test";
  }
}

being Piece an object

成为一个对象

export class Piece{
    ID: string;
    doors: string;
}

I call to test(pos)from the HTML with a valid position.

test(pos)从具有有效位置的 HTML调用。

I guess that I am trying to access to the position X of an array that has not been initialized. How could I do it? Is it possible to create a constructor?

我想我正在尝试访问尚未初始化的数组的位置 X。我怎么能做到?是否可以创建构造函数?

回答by martin

  • Correct syntax for defining array types in TypeScript is this:

    pieces: Piece[] = [];
    
  • The error is a runtime error. When you run your app you have an empty array pieces(but the variable still initialized with []) but you call test(whatever)which tries to access an array element whateverthat doesn't exist.

    You can do for example this:

    pieces: Piece[] = [{
      ID: '1',
      doors: 'foo'
    }];
    

    and then test this method with test(0).

  • 在 TypeScript 中定义数组类型的正确语法是这样的:

    pieces: Piece[] = [];
    
  • 该错误是运行时错误。当你运行你的应用程序时,你有一个空数组pieces(但变量仍然用 初始化[])但是你调用test(whatever)它试图访问一个whatever不存在的数组元素。

    例如,您可以这样做:

    pieces: Piece[] = [{
      ID: '1',
      doors: 'foo'
    }];
    

    然后使用test(0).

回答by Ekansh Rastogi

You can try the following method

你可以试试下面的方法

 test(pos){
    if(pos < this.pieces.length)
      this.pieces[pos].ID = "test";
    else
      // throw error
  }

回答by TLP

How about this?

这个怎么样?

export class Carimplements OnInit {
  pieces: Piece[] = [];

  test(pos){
    this.pieces[pos] = {ID: "test"};
  }
}

回答by Shashidhar Mayannavar

let pieces: Piece[]  = [];

//initialize object before assigning value
test(pos){
    this.pieces[pos] = new Piece();
    this.pieces[pos].ID = "test";
  }