【问题标题】:How to get values associated to a javascript dictionary如何获取与 javascript 字典关联的值
【发布时间】:2021-09-03 01:37:14
【问题描述】:

我在 html 页面的脚本标记内有这个声明的字典变量。 我想获取与“Roads”和“Intersections”键关联的值。每次刷新页面时,这些值都会更改。捕捉它们,将允许我使用 Javascript 在我的 python folium 地图上更改这些颜色:

(geo_json_cae0ea33c63e4c438678d293e5c32c0d.setStyle({'fillColor': "#FF0000", 'color': "#FF0000"});

根据建议,我尝试了这个,但我无法获得预期的结果。

var layer_control_aec3ac6e0e424b74a19b4c9d1c78ffeb = {
            base_layers : {
            },
            overlays :  {
                "Roads" : geo_json_cae0ea33c63e4c438678d293e5c32c0d,
                "Intersections" : feature_group_1c28eff59e394734be54cf676a09eae1,
            },
        };


window.onload = function() {
  for (var name in this) {
    if (name.includes("layer_control_")) {
      for(let key in this[name]) {
        console.log(key, this[name][key])
        
      }
    }
  }

};

我在控制台中得到了很多东西,除了我想要的(overlays 字典的值)

【问题讨论】:

  • 为什么不直接访问属性?比如layer_control_aec3ac6e0e424b74a19b4c9d1c78ffeb.overlays.Roads?
  • @ikhvjs 我假设变量名是由后端生成并在重新加载时更改。
  • 怎么样?除了“Roads”和“Intersections”键,该变量每次都在变化

标签: javascript html json dom-events javascript-objects


【解决方案1】:

假设您无法直接访问layer_control_aec3ac6e0e424b74a19b4c9d1c78ffeb(因为重新加载时名称会更改),您可以从window 中访问该变量:

var layer_control_aec3ac6e0e424b74a19b4c9d1c78ffeb = {
    base_layers : {
    },
    overlays :  {
        "Roads" : "geo_json_cae0ea33c63e4c438678d293e5c32c0d",
        "Intersections" : "feature_group_1c28eff59e394734be54cf676a09eae1",
    },
};


window.onload = function(){
    for (const name in this){
        if (name.includes("layer_control_")){
            let { Roads, Intersections } = window[name].overlays;
            console.log(Roads, Intersections);

            // Roads.setStyle({'fillColor': "#FF0000", 'color': "#FF0000"});
            // ...
        }
    }
};

您最初使用for (var name in this) 的方法是正确的。
但是,name 只包含变量的名称(字符串),而不是它的值。

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多