在脚本类型数组 [英] Arrays in type script
问题描述
我发现很难在声明数组打字稿和访问它。
I am finding difficulty declaring array in typescript and accessing it.
下面是code为我工作
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);
--------------------------------------------------------------
当我改变我的code如下试图值分配给数组项时失败。
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.
请建议....感谢
推荐答案
这是一个非常C $ C $的C#类型:
This is a very c# type of code:
var bks: Book[] = new Book[2];
在使用Javascript /打字稿你不分配内存,前面那样,这意味着完全不同的东西。这是你会怎么做你想做的事:
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;
现在解释什么新集[2];
意味着什么。这实际上意味着,调用新的运算符书[2]的数值。例如:
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]
,你应该看到哎。 <一href=\"http://www.typescriptlang.org/Playground/#src=class%20Book%20%7B%0A%20%20%20%20public%20BookId%3a%20number;%0A%20%20%20%20public%20Title%3a%20string;%0A%20%20%20%20public%20Author%3a%20string;%0A%20%20%20%20public%20Price%3a%20number;%0A%20%20%20%20public%20Description%3a%20string;%0A%7D%0A%0ABook%5B2%5D%20=%20function%20%28%29%7Balert%28%22hey%22%29;%7D%0Avar%20foo%20=%20new%20Book%5B2%5D%0A%20%20%20%20%20%20\">Try它
这篇关于在脚本类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!