我想知道是否有人可以帮助我理解以下行为。如果我在node.js服务器上有一个app.js文件,如下所示:
var http = require('http');
var _ = require('underscore');
http.createServer(function(request, response) {
var x = '';
_.each([1, 2, 3], function(num){
x +=" underscore.js says " + num;
});
response.writeHead(200, {
'Content-Type': 'text/html'
})
response.end(x);
}).listen(3000, null);然后,每次我请求该页面时,我都会看到文本"underscore.js say x“3次。我预计这是因为循环中有3个数字,并且x在每次请求时都会被重置。但是,如果我有以下内容(x移出了createServer的回调):
var http = require('http');
var _ = require('underscore');
var x = ''; // Note x is moved outside the createserver callback
http.createServer(function(request, response) {
_.each([1, 2, 3], function(num){
x +=" underscore.js says " + num;
});
response.writeHead(200, {
'Content-Type': 'text/html'
})
response.end(x);
}).listen(3000, null);第一次加载产生3个结果(不出所料),但随后的请求总是将循环追加两次(因此6 "underscore.js表示x“行。我可以理解它每次都附加到同一个变量,但我希望它每次都以3的倍数输出结果,所以第一次调用打印3行,第二次打印6行,第三次打印9行,依此类推。
我是node.js的新手,所以如果有人能解释一下这个行为,或者这个循环是如何以我想不到的方式工作的,我将不胜感激。
谢谢
发布于 2012-07-06 21:06:23
这可能是一个令人失望的答案,但仍然。
您的浏览器将向/favicon.ico发出一个HTTP请求,它将命中您的脚本,并为每个请求向您的x变量添加额外的3行。
当您刷新页面时,会看到3行。如果您刷新页面,会看到6行+3个additional.
/favicon.ico,另外会添加3行代码< /favicon.ico >G213>。<
..。等。
你可以通过检查以favicon.ico结尾的request.url参数来解决这个问题;
if (/\/favicon.ico$/.test(request.url)) {
// don't incremement
}..。或者你可以用url() module;做得更恐怖一些。
if (require('url').parse(request.url).pathname === '/favicon.ico') {
// don't incremement.
}https://stackoverflow.com/questions/11362565
复制相似问题