如何在 TypeScript 中使用键值对实例化数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40772874/
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
How to instantiate an array with key-value pairs in TypeScript?
提问by Marco Roy
I want to instantiate an array of key-value pairs in one step, but I can't figure out how. Auto-numbering won't work in my use-case. I can only make it work in two steps:
我想在一个步骤中实例化一组键值对,但我不知道如何实例化。自动编号在我的用例中不起作用。我只能分两步让它工作:
let army: string[] = [];
army[100] = 'centuria';
army[1000] = 'legion';
...
let army: string[] = [];
army[100] = 'centuria';
army[1000] = 'legion';
...
What I'd like to be able to do, which is available in most other programming languages:
我希望能够做的事情,在大多数其他编程语言中都可以使用:
let army: string[] = [
100 => 'centuria',
1000 => 'legion',
...
];
let army: string[] = [
100 => 'centuria',
1000 => 'legion',
...
];
Is there any way to do this in TypeScript?
有没有办法在 TypeScript 中做到这一点?
Edit:I can't use an object as I need to pass the data to an interface which is expecting an array.
编辑:我不能使用对象,因为我需要将数据传递给需要数组的接口。
回答by Nitzan Tomer
There's no such functionality in javascript, but you can easily create it:
javascript 中没有这样的功能,但您可以轻松创建它:
function arrayFactory<T>(obj: { [key: number]: T }): T[] {
let arr = [];
Object.keys(obj).forEach(key => {
arr[parseInt(key)] = obj[key];
});
return arr;
}
let arr = arrayFactory({ 100: "centuria", 1000: "legion" });
console.log(arr); // [100: "centuria", 1000: "legion"]
(操场上的代码)
The question is why not using an object as key/map to store this data? What different does it make to use an array (which is basically an object itself)?
问题是为什么不使用对象作为键/映射来存储这些数据?使用数组(基本上是一个对象本身)有什么不同?