简体   繁体   English

如何在没有 for 循环的情况下动态创建 Javascript/Typescript Map?

[英]How to create a Javascript/Typescript Map dynamically without for loop?

I want to dynamically create a Typescript Map<string, Person> object where Person is a class.我想动态创建一个 Typescript Map<string, Person> object,其中Person是 class。

I can use for loop to create a map like this:我可以使用for循环创建一个 map,如下所示:

function getInitializedPersonMap(size){
  const personMap = new Map<string, Person>();
  for (let index = 0; index < size; index++) {
    personMap.set(index.toString(), {} as Person);
  }
  return personMap;
}

However, I am trying to build a habit of moving away from 'for' loops and use functions like map, filter, reduce.但是,我正在尝试养成远离“for”循环并使用 map、过滤器、减少等功能的习惯。

My attempt without loop looks like this which is not quite as readable as one with for loop:我没有循环的尝试看起来像这样,它不像使用for循环的那样可读:

function getInitializedPersonMap(size){
   return new Map<string, Person>(
      Array.from(new Array(size), (_, index) => [
        index.toString(),
        {} as Person,
      ])
    );
}

For scenarios like this is this an overkill to avoid 'for' loops?对于这样的场景,这是避免“for”循环的过度杀伤力吗?

You can use Map , notice the type has been explicitly mentioned.您可以使用Map ,请注意已明确提及类型。

var result = sizeArr.map((i): [string, Person] => [i, {} as Person]);

As @VLAZ mentioned that size is an number, so use Array.from to flatten the array from target size.正如@VLAZ 提到的大小是一个数字,所以使用Array.from将数组从目标大小展平。

let sizeArr = Array.from(Array(n).keys());

If from the very beginning you know the values, then is pretty straightforward:如果从一开始你就知道这些值,那么就很简单了:

  const personMap = new Map<string, Person>([
    ['value1', new Person()],
    ['value2', new Person()],
    ['value3', new Person()]
  ]);

If what you want is to create the Map based on some existing generated Array, then you can:如果您想要基于一些现有的生成数组创建 Map,那么您可以:

const arrayLength = 5;
const inputArray = Array.from({ length: arrayLength }, (_, index) => [index + '', new Person()]);

const theMap = new Map<string, Person>(
  inputArray.map(x => [x[0], x[1]] as [string, Person])
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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