[英]How can I define an object based array in TypeScript?
In Javascript, I can define a collection using an object, something like this: 在Javascript中,我可以使用对象定义集合,如下所示:
var myArray = {};
myArray['some-key1'] = new CustomObject('param1');
myArray['some-key2'] = new CustomObject('param2');
myArray['some-key3'] = new CustomObject('param3');
In TypeScript, can I have a collection based on object's properties, like in Javascript? 在TypeScript中,是否可以像Javascript中那样基于对象的属性进行收集?
Another question, if I have 100 elements in one collection, what would be faster - storing these items in a classic array ( myarray.push(instanceObj)
), or storing them as properties of objects? 另一个问题,如果我在一个集合中有100个元素,哪个会更快-将这些项目存储在经典数组(
myarray.push(instanceObj)
)中,还是将它们存储为对象的属性?
If you have a fixed number of keys, the best thing to do is: 如果您有固定数量的键,则最好的方法是:
const myObject = {
"some-key1": new CustomObject("param1"),
"some-key2": new CustomObject("param2"),
"some-key3": new CustomObject("param3"),
}
Note that now even something like this typechecks: 请注意,现在即使是这种类型的东西也会检查:
myObject["some-key1"] // TypeScript correctly infers the type to be CustomObject!
If you can't do that, the best way is to use an index type: 如果不能这样做,最好的方法是使用索引类型:
let myObject: { [key: string]: CustomObject };
which indicates to TypeScript that myObject maps strings to CustomObjects. 这向TypeScript指示myObject将字符串映射到CustomObjects。
Another question, if I have 100 elements in one collection, what would be faster - storing these items in a classic array (myarray.push(instanceObj)), or storing them as properties of objects?
另一个问题,如果我在一个集合中有100个元素,哪个会更快-将这些项目存储在经典数组(myarray.push(instanceObj))中,还是将它们存储为对象的属性?
It really depends on what you're planning to do with the array/object. 这实际上取决于您计划对数组/对象执行的操作。 What's your use case?
您的用例是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.