类型脚本中的数组 [英] Arrays in type script

查看:153
本文介绍了类型脚本中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



下面是适用于我的代码

  --------------------------------------- --------------- 
class Book {
public BookId:number;
public标题:string;
public作者:string;
public价格:number;
public描述: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;

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

解决方案

这是一个非常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 =新书[2]

尝试


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.

解决方案

This is a very c# type of code:

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:

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.:

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

and you should see hey. Try it

这篇关于类型脚本中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆