gpt4 book ai didi

javascript - JavaScript 中数组到字符串的转换

转载 作者:行者123 更新时间:2023-11-28 16:05:38 25 4
gpt4 key购买 nike

附件是有问题的代码。

var http = require("http");
var i = 0;

var hostNames = ['www.1800autoland.com','www.youtube.com','www.1800contacts.com'];

for(i;i<hostNames.length;i++){
var options = {
host: hostNames[i],
path: '/'
};
http.get(options, function(res){
console.log("url: " + hostNames[i]);
console.log("status: " + res.statusCode);

for(var item in res.headers){
if(item == "server"){
console.log(item + ": " + res.headers[item]);
}
if(item == "x-powered-by"){
console.log(item + ": " + res.headers[item]);
}
if(item == "x-aspnet-version"){
console.log(item + ": " + res.headers[item]);
}
}
console.log("\n");
})
};

我有一个 URL 数组,我来咨询该网站的问题是,在我的代码中,hostNames[i] 没有将第 n 个(或本例中的“i”)索引显示为字符串。控制台中的输出始终是“未定义”。我尝试过 String()、toString() 和许多不同的方法,但均无济于事。有人能指出我正确的方向吗?我需要做什么转换?

最佳答案

这是一个典型的由于异步而发生的闭包问题。当您的回调触发时,i 的值将始终为 hostNames.length

要修复它关闭围绕i的值:

http.get(options, (function(res) { // '(' before function is optional, I use it to indicate immediate invocation
return function (i) { // this is the closed value for i
console.log("url: " + hostNames[i]);
console.log("status: " + res.statusCode);
// .. etc
};
}(i))); // immediate invocation with i

关于使用这样的闭包,需要意识到的重要一点是,您正在创建许多匿名函数,而不仅仅是一个。每个函数都绑定(bind)到它自己的 i 值。

<小时/>

避免编写这些奇怪代码的最简单方法是不直接使用 for 循环,而是使用 map 函数。喜欢:

function array_map(array, callback) {
var i, len = array.length;
for (i = 0; i < len; i += 1) {
callback(i, array[i]);
}
}

这使得您自动关闭i的值。您的循环将如下所示:

array_map(hostNames, function(i, hostname) { // i and hostname have the closed value
// .. etc
});

关于javascript - JavaScript 中数组到字符串的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15072727/

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