如何处理node.js中的循环?
我在node.js中有以下代码
var months = ['jan','feb','march','april','may','june','july','august','sep','oct','nov','dec'] for(var i=0; j=months.length,i<j; i++){ var start = scope.getCurrentUTS(new Date(2013, i, 1)); var end = scope.getCurrentUTS(new Date(2013, i, 31)); var query = {}; query["stamps.currentVisit"] = { "$gte" : start.toString(), "$lt" : end.toString() }; //connect to mongo and gets count coll.find(query).count(); working fine mongoDB.getCount(query,function(result) { console.log(result,i); }); }
问题:代码正在运行asynchronous,最后一行代码没有按预期运行。
预期的产出是
10 0
11 1
12 2
…….
……..
40 11
但它是作为输出
undefined 11
任何帮助将是伟大的
可能有些查询不匹配任何内容。 这就是为什么它返回未定义的结果。 但还有另一个问题。 我在asynchronouscallback可能不是你所期望的。 而且可能会等于months.length 。 为了保持相同的我你应该使用像这样的东西:
var months = ['jan','feb','march','april','may','june','july','august','sep','oct','nov','dec'] for(var i=0; j=months.length,i<j; i++){ (function(i) { var start = scope.getCurrentUTS(new Date(2013, i, 1)); var end = scope.getCurrentUTS(new Date(2013, i, 31)); var query = {}; query["stamps.currentVisit"] = { "$gte" : start.toString(), "$lt" : end.toString() }; //connect to mongo and gets count coll.find(query).count(); working fine mongoDB.getCount(query,function(result) { console.log(result,i); }); })(i); }
另外这个
for(var i=0; j=months.length,i<j; i++){
可能只是:
for(var i=0; i<months.length; i++){