简体   繁体   中英

How to instantiate an array with key-value pairs in TypeScript?

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'; ...

What I'd like to be able to do, which is available in most other programming languages:

let army: string[] = [ 100 => 'centuria', 1000 => 'legion', ... ];

Is there any way to do this in TypeScript?

Edit: I can't use an object as I need to pass the data to an interface which is expecting an array.

There's no such functionality in javascript, but you can easily create it:

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"]

( code in playground )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM