39

我发现很难在打字稿中声明数组并访问它。

下面是为我工作的代码

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;

对我来说,要在循环中添加对象,我必须采用第二种方式。

4

3 回答 3

68

这是一个非常 C# 类型的代码:

var bks: Book[] = new Book[2];

在 Javascript / Typescript 中,您不会像那样预先分配内存,这意味着完全不同的东西。这就是你将如何做你想做的事:

var bks: Book[] = [];
bks.push(new Book());
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;

现在解释一下new Book[2];这意味着什么。这实际上意味着在 Book[2] 的值上调用 new 运算符。例如:

Book[2] = function (){alert("hey");}
var foo = new Book[2]

你应该看到嘿。试试看

于 2013-04-26T09:56:45.117 回答
16

您也可以这样做(更快捷),而不必进行实例声明。您改为在 JSON 中执行此操作。

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.
于 2016-04-25T16:37:56.793 回答
-1

一种更清洁的方法:

class Book {
    public Title: string;
    public Price: number;
    public Description: string;

    constructor(public BookId: number, public Author: string){}
}

然后

var bks: Book[] = [
    new Book(1, "vamsee")
];
于 2016-02-22T00:09:05.887 回答