Javascript将函数的结果传递到一个spoolet.js项目中的另一个函数中
我正在使用传单和geoJson数据进行一个项目。我正在制作一个choropleth映射,我试图将一个函数的结果传递给另一个函数。我不认为这种情况是传单所独有的,我认为当涉及到将一个函数的结果作为另一个函数的参数传递时,我只是绊倒了 我有一个函数,它根据从API中提取的GDP值为地图中的国家设置样式:Javascript将函数的结果传递到一个spoolet.js项目中的另一个函数中,javascript,function,parameters,leaflet,closures,Javascript,Function,Parameters,Leaflet,Closures,我正在使用传单和geoJson数据进行一个项目。我正在制作一个choropleth映射,我试图将一个函数的结果传递给另一个函数。我不认为这种情况是传单所独有的,我认为当涉及到将一个函数的结果作为另一个函数的参数传递时,我只是绊倒了 我有一个函数,它根据从API中提取的GDP值为地图中的国家设置样式: function getColor(d) { return d > 1000000 ? '#005824' : d > 500000 ? '#238b
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个硬编码作为getColor函数的参数。我想对此进行更改,以便将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(gdp){
对于(变量i=0;ifunction 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
};
}
功能样式(功能){
返回{
//fillColor:getColor(100000),
fillColor:getColor(函数(d){
对于(变量i=0;i
与此类似,如(添加一些颜色)一节所示,您只需意识到传单工厂将循环通过您传递的功能数据,并为每个功能调用一次函数,将单个功能数据作为style
函数的参数,因为问题中的代码已经设置好了
由于您肯定希望使用与单个功能相关联的数据调用getColor
函数(以便后者根据其数据而不是所有其他功能的数据进行样式设置),您知道,尝试使用getGDP
函数循环所有功能并尝试在style
函数中使用所有这些数据会适得其反
功能样式(功能){
返回{
fillColor:getColor(feature.properties.gdp\u md\u est),
//等等。
};
}
getColor(getGDP(??))
-由于您没有显示如何调用getGDP,因此不确定应该是什么?
。。。当您在上迭代时,可能是错误的。。。而且还没有说明.gdp\u md\u est
如何与100000
相关,更好的方法是将回调函数传递给样式函数内部的getColor?我想去掉硬编码的100000值,并将API/getGDPFirstly中的迭代数据传递给getColor,您没有在getGDP中进行迭代-返回确保始终返回countriesData.features[0].properties.gdp\u md\u est
-请注意0
,而不是i
。另外,我认为在fillColor
和您希望getGDP
返回的未显示内容之间有一个重要的“链接”。你知道你想要什么,但你还没有解释它在所有FillColor需要是一个单一的值,它不能迭代,它是一个样式属性