类型脚本中的数组

时间:2013-04-26 09:36:59

标签: arrays class object typescript

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

下面是为我工作的代码

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;

对于我在循环中添加对象,我必须以第二种方式进行。

3 个答案:

答案 0 :(得分:66)

这是一种非常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]
你应该看到嘿。 Try it

答案 1 :(得分:15)

你也可以这样做(短切)而不必做实例声明。你用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.

答案 2 :(得分:-1)

更简洁的方法:

var text_to_find = "<[SBG]>";
var findRx = new RegExp( escapeRegExp( text_to_find ) );

// Use findRx here ..

然后

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

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