簡體   English   中英

如何在沒有 for 循環的情況下動態創建 Javascript/Typescript Map?

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

我想動態創建一個 Typescript Map<string, Person> object,其中Person是 class。

我可以使用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;
}

但是,我正在嘗試養成遠離“for”循環並使用 map、過濾器、減少等功能的習慣。

我沒有循環的嘗試看起來像這樣,它不像使用for循環的那樣可讀:

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

對於這樣的場景,這是避免“for”循環的過度殺傷力嗎?

您可以使用Map ,請注意已明確提及類型。

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

正如@VLAZ 提到的大小是一個數字,所以使用Array.from將數組從目標大小展平。

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

如果從一開始你就知道這些值,那么就很簡單了:

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

如果您想要基於一些現有的生成數組創建 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