【问题标题】:Passing a variable to inline function within a for loop in javascript在javascript的for循环中将变量传递给内联函数
【发布时间】:2014-07-11 11:49:38
【问题描述】:

我一直在努力解决这个问题

var http = require('http'),
    parseString = require ('xml2js').parseString;

for (var noOfZones = 1; noOfZones<=8; noOfZones++) {
    var newPath = 'http://192.168.1.200/getZoneData?zone='+noOfZones;
    var req = http.request(newPath, function(zres, noOfZones) {
        zres.setEncoding('utf8');
        zres.on('data', function (zonedata) {
            parseString(zonedata, {
                trim:true,
                childkey:9,
                explicitArray:false,
                explicitChildren:false
            }, function (err, zones) { 
                   console.log(noOfZones);//this one bring back undefined
            });
         });
     });
     req.on('error', function(e) {
        console.log('problem with request: ' + e.message)
     })
     req.end();
}

for 循环可以将 noOfZones 传递给 newPath。但是,该值未在函数内传递(错误,区域) 我一直在阅读有关将变量传递给内联函数的内容,并试图将其放置在各个级别,但它似乎对我不起作用。我得到的只是未定义的。 (即使我把它串起来)

【问题讨论】:

  • Google 搜索“臭名昭著的循环问题 javascript”

标签: javascript function for-loop inline


【解决方案1】:

是什么让您认为 request 会将其他参数传递给您的回调?

您可以执行以下操作:

var http = require('http'),
    parseString = require ('xml2js').parseString;

Array.apply(null, new Array(8)).forEach(function(_, i) { //make iterable array
    var noOfZones = i + 1; //define scope variable
    var newPath = 'http://192.168.1.200/getZoneData?zone='+noOfZones;
    var req = http.request(newPath, function(zres) {
        zres.setEncoding('utf8');
        zres.on('data', function (zonedata) {
            parseString(zonedata, {
                trim:true,
                childkey:9,
                explicitArray:false,
                explicitChildren:false
            }, function (err, zones) { 
                   console.log(noOfZones); //access it
            });
         });
     });
     req.on('error', function(e) {
        console.log('problem with request: ' + e.message)
     })
     req.end();
});

【讨论】:

【解决方案2】:

如果您在循环声明中去掉 noOfZones 之前的“var”,应该可以工作。 所以for (noOfZones = 1; noOfZones&lt;=8; noOfZones++) 而不是for (var noOfZones = 1; noOfZones&lt;=8; noOfZones++)

【讨论】:

  • 谢谢...似乎带回了一些东西。然而,它现在是我的“目标”值 +1 (9)
  • 嗯 -1 用于推广全局变量。这不会帮助所有函数共享相同的noOfZones 值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
  • 2021-05-31
  • 2021-06-21
相关资源
最近更新 更多