使用窗口更改全局变量不起作用

时间:2018-12-23 21:28:19

标签: javascript function global-variables

我在javascript中有以下代码:

var max = 0;                                             //<---- HERE

var request = new XMLHttpRequest();
request.open('GET', 'HERE_GOES_API_ADDRESS', true);
request.onload = function (max) {                         //<---- HERE

  // Begin accessing JSON data here
  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    data.forEach(LoginLog => {

      window['max'] = LoginLog.id;                        //<---- HERE


    });
  } else {
    const errorMessage = document.createElement('marquee');
    errorMessage.textContent = `Gah, it's not working!`;
    app.appendChild(errorMessage);
  }

}

request.send();

console.log(max);                                      // <---- HERE Gives 0

循环后max的期望值为2。但是,我总是得到0

window为什么不起作用?全局变量时不应该使用?

附注:我必须全局更新max变量。 console.log(max)仅用于测试目的。

1 个答案:

答案 0 :(得分:0)

事件回调函数始终自动将它们正在处理的事件作为第一个参数传递给它,因此在您编写时:

request.onload = function (max) { 

您实际上并没有将max传递给该函数,而是在声明一个函数自变量以接收调用该函数时传递给该函数的第一个参数。发生这种情况时,将是load对象的request事件,并且该事件的计算结果为多个0。如果要在回调中访问全局变量,只需直接将其引用为max即可,不要同时为回调函数设置参数。

编辑:

除了上述问题外,您还有console.log(max);位于异步之外的事实。回调意味着它将在异步之前运行。操作完成。移动该语句,使其位于回调内部。

var max = 0; 

var request = new XMLHttpRequest();
request.open('GET', 'HERE_GOES_API_ADDRESS', true);
request.onload = function () {    // No argument needed

  // Begin accessing JSON data here
  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    data.forEach(LoginLog => {

      max = LoginLog.id;  // Just use the global
      console.log(max);   // Access the async result in the callback
    });
  } else {
    const errorMessage = document.createElement('marquee');
    errorMessage.textContent = `Gah, it's not working!`;
    app.appendChild(errorMessage);
  }

}

request.send();
相关问题