【问题标题】:Typescript how to call and access dictionary keys from a loop打字稿如何从循环中调用和访问字典键
【发布时间】:2020-03-11 19:11:56
【问题描述】:

我有一本像下面这样的字典

let dict = {
             a:{
                first:1, 
                second:2
               },
             b:{
                first:2, 
                second:3
               }
           }

我想遍历第一组键,然后操作第二组键。类似于下面的代码:

    for(const firstKey of dict){
        firstKey.first = 5
    }

问题是编译器在firstKey.first = 5saying 上给我一个错误

Property 'first' does not exist on type 'string'. 

为什么会这样?我也试过firstKey[first],但也没有用。

【问题讨论】:

    标签: javascript typescript dictionary javascript-objects


    【解决方案1】:

    键是不可迭代的。您需要使用 Object.keys() 来获取要迭代的键数组,因此:

    for(const key of Object.keys(dict)) { 
       console.log(key, dict[key]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2022-01-12
      • 2019-09-24
      • 1970-01-01
      相关资源
      最近更新 更多