typescript 类型脚本中的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16233266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:04:00  来源:igfitidea点击:

Arrays in type script

arraysclassobjecttypescript

提问by VKR

I am finding difficulty declaring array in typescript and accessing it.

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

below is the code working for me

下面是对我来说有效的代码

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);

When I change my code as below it fails when trying to assign value to array item.

当我如下更改我的代码时,它在尝试为数组项分配值时失败。

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

For me to add object in a loop I have to do it the second way.

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

回答by basarat

This is a very c# type of code:

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

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

In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:

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

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

Now to explain what new Book[2];would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:

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

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

and you should see hey. Try it

你应该看到嘿。尝试一下

回答by fletchsod

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

您也可以这样做(更快捷),而不必进行实例声明。您可以在 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.

回答by Serj Sagan

A cleaner way to do this:

一个更干净的方法来做到这一点:

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

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

Then

然后

var bks: Book[] = [
    new Book(1, "vamsee")
];