代码之家  ›  专栏  ›  技术社区  ›  Nick Kinlen

javscript将函数的结果传递到fluel.js项目中的另一个函数中

  •  0
  • Nick Kinlen  · 技术社区  · 6 年前

    我在做一个使用fluel.js和geojson数据的项目。我正在制作一张图层地图,我试图把一个函数的结果传递给另一个函数。我不认为这种情况对于传单是独特的,我认为当把一个函数的结果作为另一个函数的参数时,我只是绊倒了。

    我有一个功能,可以根据从API中提取的GDP值对地图中的国家进行样式设置:

     function getColor(d) {
          return d > 1000000 ? '#005824' :
              d > 500000  ? '#238b45' :
              d > 200000  ? '#41ae76' :
              d > 100000  ? '#66c2a4' :
              d > 50000   ? '#99d8c9' :
              d > 20000   ? '#ccece6' :
              d > 15000   ? '#edf8fb':
                           '#fff'
        }
    

    此函数由第二个函数调用:

      function style(feature) {
          return {
              fillColor: getColor(100000),
              weight: 2,
              opacity: 1,
              color: 'white',
              //dashArray: '3',
              fillOpacity: 0.7,
              stroke: true,
              weight: .5,
              fill: true,
              clickable: true
          };
        }
    

    正如您所看到的,当前我有100000个硬编码作为GETCURE函数的参数。我想更改此设置,以便将来自api的数据传递给getcolor,而不是此硬编码值。

    我有一个从api中提取的gdp数据,我可以使用以下函数对其进行console.log操作:

    function getGDP(gdp) {
          for(var i = 0; i < countriesData.features.length; i++) {
           console.log(countriesData.features[i].properties.name + ' ' + countriesData.features[i].properties.gdp_md_est);
           return countriesData.features[i].properties.gdp_md_est;
          }
        } 
    

    如何将getGDP()函数的结果传递给style()函数中的getColor()函数?

    这需要关闭吗?如果是,如何使用闭包来完成此操作?我不相信这个问题是单张或这个项目的独家,我想我只是有麻烦围绕如何通过一个功能返回值的另一个函数嵌套在一个第三功能我的头。

    getcolor函数必须在 countriesdata.features[i].properties.gdp最新 元素。

    像这样的工作:

    function style(feature) {
          return {
              //fillColor: getColor(100000),
              fillColor: getColor(function(d) {
                for(var i = 0; i < countriesData.features.length; i++) {
                 var data =  countriesData.features[i].properties.gdp_md_est;
                 return data;
                }
              }),
              weight: 2,
              opacity: 1,
              color: 'white',
              //dashArray: '3',
              fillOpacity: 0.7,
              stroke: true,
              weight: .5,
              fill: true,
              clickable: true
          };
        }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   ghybs    6 年前

    与另一个类似 recent question 如图所示 Leaflet choropleth map tutorial (“添加一些颜色”一节),您只需了解传单 L.geoJSON 工厂将循环遍历您传递给它的特性数据,并调用 style 功能 每个功能一次 ,将单个要素数据作为 风格 函数,因为问题中的代码已经设置好。

    既然你真的想打电话给你 getColor 函数的数据与该单一功能相关(这样后者就可以根据其数据而不是所有其他功能的数据来设置样式),您可以理解,尝试循环使用会适得其反 全部 您的功能 getGDP 函数并尝试使用 风格 功能。

    function style(feature) {
      return {
        fillColor: getColor(feature.properties.gdp_md_est),
        // etc.
      };
    }