初始化对象数组 - Angular

15

我有一个对象数组,当我尝试访问它时,会出现以下错误:

TypeError: 无法设置未定义的属性 'ID'

我的代码如下:

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

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

作为对象的一部分

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

我在HTML中使用一个有效的位置调用了test(pos)

我猜我试图访问一个未初始化的数组的第X个位置。我该怎么做?是否可以创建一个构造函数?


你的意思不是应该这样写吗:pieces: Piece[] = []; - kshetline
是的,抱歉,那只是一个打字错误。但是错误仍然存在。 - bellotas
4个回答

19
  • 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 whatever that doesn't exist.

    You can do for example this:

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

    and then test this method with test(0).


pieces = Piece[] = [] 只是一个打字错误。我的意思是 pieces: Piece[] = []; 但是错误仍然存在。 - bellotas
你能制作一个演示吗? - martin

1
这个怎么样?
export class Carimplements OnInit {
  pieces: Piece[] = [];

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

1
let pieces: Piece[]  = [];

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

0
您可以尝试以下方法。
 test(pos){
    if(pos < this.pieces.length)
      this.pieces[pos].ID = "test";
    else
      // throw error
  }

不,Pos 是正确的。实际上,在这种情况下我正在尝试访问 pos = 0,即第一个位置。 - bellotas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接