for 循环不工作打印不正确的值。需要索引

for loop not working printing incorrect values. need index

我无法理解为什么 for 循环不能正常工作

for (x = 0; x < 10; x++) { 
url= 'http://capc-pace.phac-aspc.gc.ca/details-eng.php?project='+x;
urllib.request(url, function (err, data, res) {
    if (err || res.statusCode !=200) {
    }
    else{
    console.log(x);
    }
});
}

我总是得到这个作为我的回应

s452:scripts 04101frt$ node javascriptparser.js 
10
10
10
10
10

我希望获得所有没有重定向的页面(即它们在 url 中的编号)

数字的数量很好(在本例中为 5 个),但我想要它们的正确值。

所以,您正在使用闭包,是吗?

闭包是在匿名函数中从父范围捕获变量 x 的东西。 x 将始终引用该变量分配的最后一个值,即使 "created" 该变量的函数早已完成。

您需要在每个步骤中传递变量值的副本。像这样:

for (x = 0; x < 10; x++) { 
  url= 'http://capc-pace.phac-aspc.gc.ca/details-eng.php?project='+x;
  (function (x) {
    urllib.request(url, function (err, data, res) {
      if (err || res.statusCode !=200) {
      }
      else{
        console.log(x);
      }
    }
  })(x);
}

看看我们做了什么?新的立即调用函数表达式 (IIFE) 为其参数接收一个值。这样我们就有效地创建了循环计数器的 10 个副本。 console.log(x)指的是这个参数,不是外循环计数器。

您在此处 运行 的内容是由 javascript 的函数级别范围引起的。花点时间阅读这篇文章——它很好地解释了正在发生的事情 http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

这里有一个 fiddle 可以更形象地说明问题 -

http://jsfiddle.net/tm604oLu/

var url;
//wrong: because of being all on the same scope the value of x is 9 at the time it's evaluated
for (x = 0; x < 10; x++) {
    url = 'http://capc-pace.phac-aspc.gc.ca/details-eng.php?project=' + x;
    setTimeout(function () {
        console.log(url);
    }, 1);
}

//correct behavior: by passing the url as the parameter to a function you are creating a new 'scope' and the value does not get overwritten
for (x = 0; x < 10; x++) {
    url = 'http://capc-pace.phac-aspc.gc.ca/details-eng.php?project=' + x;
    (function (ownScope) { 
        setTimeout(function () {
            console.log(ownScope);
        }, 1);
    }(url));
}

通过创建 IFFE(立即调用的函数表达式),您创建了一个新范围 - 这有助于保留计数器的预期值。