【问题标题】:Declare a dictionary with explicit types node.js声明具有显式类型 node.js 的字典
【发布时间】:2017-12-29 18:13:16
【问题描述】:

我正在使用 node.js:

var cart = {}

我在一个 for 循环中

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

当然,购物车中总会有一个元素。

我想做这样的事情:

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

有办法巧妙地做到这一点吗?

【问题讨论】:

    标签: javascript node.js dictionary


    【解决方案1】:
     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;
       }
    }
    

    所以可以这样做:

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

    【讨论】:

      【解决方案2】:

      你可以像这样初始化一个包含元素的数组:

      cart[id] = [element];
      

      【讨论】:

        猜你喜欢
        • 2022-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-23
        • 2020-08-04
        • 2019-07-20
        相关资源
        最近更新 更多