我发现很难在打字稿中声明数组并访问它.
下面是为我工作的代码
class Book {
public BookId: number;
public Title: string;
public Author: string;
public Price: number;
public Description: string;
}
class dataservice {
getproducts() {
var bk = new Book();
bk.Author = "vamsee";
bk.BookId = 1;
var bks: Book[] = [bk,bk];
return bks.length;
}
}
var ds = new dataservice();
var button = document.createElement('button');
button.onclick = function () {
alert(ds.getproducts().toString());
}
document.body.appendChild(button);
Run Code Online (Sandbox Code Playgroud)
当我更改我的代码时,它尝试为数组项分配值时失败.
var bks: Book[] = new Book[2];
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;
Run Code Online (Sandbox Code Playgroud)
对于我在循环中添加对象,我必须以第二种方式进行.