【问题标题】:Javascript nested functions variable is not defined [duplicate]Javascript嵌套函数变量未定义[重复]
【发布时间】:2022-01-03 13:40:07
【问题描述】:

我在这里想要实现的是为 4 个区域中的每一个构建一个包含平均 SLA 的图表。为此,我调用一个 API 来获取一些 id,我使用这些 id 来调用另一个 API 并获取 SLA。然后,我正在计算平均 SLA。我必须为每个地区做 4 次。最后,我想要 2 个包含区域名称和平均 SLA 的数组,这样我就可以构建图表。问题是,我无法从这些嵌套函数中获取 SLA 数据,因此我可以构建数组。它告诉我变量是未定义的。

所以问题是为什么我一离开函数就不能访问average var?我尝试使用return average;。我还尝试从function(response)function(data) 返回。这是我写的第一个 JS,我觉得它有很大的问题。你能帮我看看是什么吗?

// This is the fetch that gets me the SLAs and where I calculate the averages. 

function regionsla(serviceids, regionName) {
  fetch('api.php', {
    // request body
  }).then(
    function(response) {
      response.json().then(
        function(data) {
          var i = 0;
          var sum = 0;
          var labels = [];
          var values = [];

          for (const label in data.result) {

            sum = sum + data.result[label].sla[0].sla;
            i++;
          }

          average = sum / i;

          labels.push(regionName);
          values.push(average);
        }
      )
    }
  );
}

// This is the main function that runs in the beginning. The fetch is inside a for loop and it will get me the IDs that I need in order to run function regionsla.

async function get_sla() {
  regionsids = [58, 59, 60, 61];
  americaids = [];
  europeids = [];
  asiaids = [];
  australiaids = [];
  for (const regionid of regionsids) {
    fetch('api.php', {
      // request body
    }).then(
      function(response) {
        response.json().then(
          function(data) {
            for (const label in data.result) {
              switch (regionid) {
                case 58:
                  americaids.push(data.result[label].serviceid);
                  break;
                case 59:
                  australiaids.push(data.result[label].serviceid);
                  break;
                case 60:
                  asiaids.push(data.result[label].serviceid);
                  break;
                case 61:
                  europeids.push(data.result[label].serviceid);
              }
            }
            switch (regionid) {
              case 58:
                regionsla(americaids, "America");
                averageAmerica = average;
                console.log(averageAmerica); //this returns                                                                          
                break; // average is not defined
              case 59:
                regionsla(australiaids, "Australia");
                break;
              case 60:
                regionsla(asiaids, "Asia");
                break;
              case 61:
                regionsla(europeids, "Europe");
            }
          })
      }
    );
  }
}

【问题讨论】:

  • 奇怪的抓取。这是规范获取:fetch('api.php') .then(response => response.json()) .then(data => console.log(data));
  • 这是个坏主意:for (const regionid of regionsids) { fetch('api.php', {...).then( 永远不要循环 ajax。而是将下一个调用放在成功或完成的提取中
  • 最后一个带有平均值的 reduce 会更容易阅读
  • 但是获取一个区域 id 然后切换听起来也很混乱。为什么不let americaids = []; fetch (api.php?region=58)。但如果是你的 api,那么一次调用它们就足够了

标签: javascript arrays function


【解决方案1】:

问题在于变量的范围。变量只能在声明它们的函数内访问。如果要全局访问变量,请全局声明它。我可以知道在哪里声明了 Average 变量吗?

正如 cmets 中所讨论的,以下代码将为您提供一些想法。

    function showName() {
  var result;`enter code here`
  result = addString('Hello', ' World');
  document.write (result );
}

// in below we will check how to return string from function
function addString(fName, lName) {
  var val;
  val = fName + lName;
  return val;  // returning string from function
}

【讨论】:

  • 它在第一个函数中被赋值,在for循环内:average = sum / i;手册上说:“如果你给一个没有声明的变量赋值,它会自动变成一个GLOBAL变量”
  • 另外,我尝试声明 average=0;一开始,在所有函数之外,但是平均值的值将始终为0。所以问题不在于声明,而在于从一个函数跳转到另一个函数时,它的值没有被保留。跨度>
  • 我有点明白问题所在了。
  • 尝试平均1 = regionla(americaids, "America");在函数调用中。这将在 average1 中得到 return 语句。从 regionla 函数返回平均值。我在我的回答中更新了一个示例代码,让您了解函数返回的工作原理
  • 范围不是问题。由于该变量从未被声明,它成为一个全局变量或更准确地说,是window 对象上的一个属性(这是一个非常非常糟糕的主意,但这不是这里的问题)。问题是函数regionsla 进行了异步调用,因为它在没有等待异步进程完成的情况下被调用,所以下一行 (averageAmerica = average) 在设置全局变量之前运行。
猜你喜欢
  • 2018-08-31
  • 2013-04-28
  • 2016-06-16
  • 2016-12-26
  • 1970-01-01
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 2019-04-30
相关资源
最近更新 更多