简体   繁体   English

我不明白为什么我的全局变量没有更新?

[英]I don't understand why my global variable isn't updating?

I posted about this yesterday but I am still dumbfounded. 我昨天发布了这个,但我仍然傻眼了。 I can't seem to figure out this problem. 我似乎无法弄清楚这个问题。 I want to update the parkEndpoint URL with a new value for the stateName variable when the user clicks on a state SVG. 我想在用户单击状态SVG时使用stateName变量的新值更新parkEndpoint URL。 It keeps coming up as the original value in line 1. 它一直是第1行的原始值。

I have tried looking in the console and after the function getStateName runs it does update the stateName variable, but when I console log the parkEndpoint variable after that function has run, it still shows the old variable, which I just set to nothing. 我试过在控制台中查找并且在函数getStateName运行之后它确实更新了stateName变量,但是当我在该函数运行后控制台登录parkEndpoint变量时,它仍然显示旧变量,我只是设置为空。

var stateName = "";
const alertEndpoint = ("https://developer.nps.gov/api/v1/alerts? 
&limit=400&api_key=" + apikey );
var parkEndpoint = ("https://developer.nps.gov/api/v1/parks? 
stateCode=" + stateName + "&limit=100&api_key=" + apikey);

const elements = document.querySelectorAll('path');
console.log(elements);

// add event listeners
elements.forEach(function(el) {
  el.addEventListener("click",  getStateName);

});


   function getStateName(nodeList){
   stateName = nodeList.path[0].id;
   outputStateName(stateName);

 }

   function outputStateName(stateName) {
   console.log(stateName);
   console.log(parkEndpoint);
  }

I just want it to update the stateName variable in the URL. 我只是想让它更新URL中的stateName变量。

It's because you don't update the value of parkEndpoint 这是因为你没有更新parkEndpoint的值

In javascript, string are stored by reference. 在javascript中,字符串通过引用存储。 Meaning parkEndpoint references to the string defined L3, and is not reassigned later. 含义parkEndpoint引用定义为L3的字符串,以后不再重新分配。

You need to reassign it in your getStateName function. 您需要在getStateName函数中重新分配它。

Your statName variable is empty in the beginning and even after you are getting the state name from stateName = nodeList.path[0].id; 您的statName变量在开头是空的,甚至在从stateName = nodeList.path[0].id;获取状态名称之后stateName = nodeList.path[0].id; the variable parkEndpoint is never being updated. 变量parkEndpoint永远不会被更新。

var stateName = '';
var parkEndpoint = parkEndpointUpdate();

function parkEndpointUpdate(){
   return `https://developer.nps.gov/api/v1/parks?
   stateCode=${stateName}&limit=100&api_key=${apikey}`
}

function getStateName(){
   stateName = nodeList.path[0].id;
   parkEndpoint = parkEndpointUpdate(); // This func will updated your variable of parkEndPont
   outputStateName(stateName);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM