简体   繁体   中英

Declare a dictionary with explicit types node.js

I'm doing this using node.js:

var cart = {}

in a for loop I do

cart[id] = []
cart[id].push(element)

Of course there will be always one element in cart.

I want to do something like:

var cart: {'':[]} = {}

There's a way to do it in a clever way ?

您可以初始化包含以下元素的数组:

cart[id] = [element];
 class Dictionary extends Map {
   constructor(){
     super();
   }
   add(id, data){
     if(this.has(id)){
       this.get(id).push(data);
     }else{
       this.set(id, [data]);
     }
     return this;
   }
}

So one can do:

const dictionary = new Dictionary();
dictionary
  .add(1, "el")
  .add(2,"el")
  .add(1,"el2");

console.log(dictionary.get(1));

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