gpt4 book ai didi

javascript - 在 Node.js 中将循环计数器作为参数传递

转载 作者:太空宇宙 更新时间:2023-11-04 00:53:37 24 4
gpt4 key购买 nike

我尝试将此作为 Nodeschool 的教程,而且我是 Node.js 的新手。代码如下,我知道其中的问题,但我无法解决它。问题是 bl 函数内每次循环迭代时 j 的值为 3,但为什么会发生这种情况?

var bl = require('bl');
var http = require('http');
var urls = process.argv.slice(2);



var result = [];

for (var i = 0; i < urls.length; i++) {
result.push(null);
}

for(j = 0 ; j < urls.length; ++j){
http.get(urls[j],function(response){
response.pipe(bl(function(err,data){
//console.log(result[i]);
//console.log(data.toString());
result[j] = data.toString();
console.log('J : ' + j);
console.log(data.toString());
var flag = 0;
for (var i = 0; i < result.length; i++) {
console.log('here1');
console.log(result[i]);
if(result[i] == null){
flag = 1;
console.log('here');
break;
}
}
if(flag == 0){
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
}
}));
});
}

最佳答案

http.get 是一个异步请求,但 for 是同步的,因此 for 是“最快”的,当 http.get 完成下载 url 数据时,变量“j”将采用最后一个值。

我认为你还有另一个错误,在 for 循环中,你将变量“j”增加为“++j”,它将是“j++”。

要解决第一个问题(变量“j”值),您可以使用匿名函数并传递值“j”,如下所示:

for(j = 0 ; j < urls.length; j++) {
(function(j) {
http.get(urls[j],function(response){
response.pipe(bl(function(err,data){
//console.log(result[i]);
//console.log(data.toString());
result[j] = data.toString();
console.log('J : ' + j);
console.log(data.toString());
var flag = 0;
for (var i = 0; i < result.length; i++) {
console.log('here1');
console.log(result[i]);
if(result[i] == null){
flag = 1;
console.log('here');
break;
}
}
if(flag == 0){
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
}
}));
});
}(j));
}

有很多代码,但在简历中我这样做了:

for(j = 0 ; j < urls.length; j++) {
(function(j) {
/* your code inside this function will have the correct
value to variable "j" if you use async methods */
} (j));
}

关于javascript - 在 Node.js 中将循环计数器作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com