我发现很难在打字稿中声明数组并访问它。
下面是为我工作的代码
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);
当我如下更改代码时,尝试为数组项赋值时失败。
var bks: Book[] = new Book[2];
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;
对我来说,要在循环中添加对象,我必须采用第二种方式。