gpt4 book ai didi

javascript - learnyounode 练习 9 - 输出显示未定义、理解异步或逻辑的问题

转载 作者:行者123 更新时间:2023-12-03 04:45:11 25 4
gpt4 key购买 nike

我一直在努力解决 learnyounode 上的 JUGGLING ASYNC 任务。据我所知,我做的事情几乎是正确的,看起来问题出在异步的某个地方,而我自己试图避免bl或其他模块。我在没有其他模块的情况下完成了上一个任务,并希望继续这种趋势。

const http = require('http');
const url = process.argv[2];

let content = [];
let count = 0;

const arguments = process.argv;
let urlArray = arguments.filter(function pullUrls(element, index, array) {
return index >= 2;
});

function printResults() {
for (var i = 0; i < 3; i++) {
console.log(content[i]);
}
}

function httpGet(index) {
http.get(urlArray[index], function(response){
response.on('data', function(data){

newData = data.toString();
content[index] = content[index] + newData;
})
response.on('end', function(){
count++;
if (count === 3){
printResults();
}
})
})
}

for (var i = 0; i < 3; i++) {
httpGet(i);
}

常见输出非常接近预期,但在开头包含一个 undefined 字符串,我不明白为什么。

undefinedLets get some ute when we're going parma. Grab us a slab how it'll be bull bar. He's got a massive bushie where stands out like a pot. 
undefinedShe'll be right mongrel heaps as cross as a hit the turps. Stands out like a booze also you little ripper flick. As stands out like ironman when lets throw a bikkie.
undefinedHe hasn't got a bounce with gutful of struth. Stands out like a aerial pingpong piece of piss built like a battler.

正如您所看到的,它首先找到数组“未定义”,这是正确的,然后附加到它上面。

我最好的猜测是,content[index] = content[index] + newData; 行以某种方式保留了 let content = [] 的未定义性质在计算出 content[i] 之前。现在我已经把它写出来并仔细考虑了,这可能是一个简单的 JS 问题,我只是忽略了或者不知道我不知道。

任何帮助都会很好。

最佳答案

您获得了正确的输出,content[index] 最初是未定义的,您可以在连接 newData 之前进行未定义的检查。这是经过更改的完整代码。

const http = require('http');
const url = process.argv[2];

let content = [];
let count = 0;

const arguments = process.argv;
let urlArray = arguments.filter(function pullUrls(element, index, array) {
return index >= 2;
});

function printResults() {
for (var i = 0; i < 3; i++) {
console.log(content[i]);
}
}

function httpGet(index) {
http.get(urlArray[index], function(response){
response.on('data', function(data){

let newData = data.toString();
//check if undefined
if(typeof content[index] !== 'undefined'){
content[index] = content[index] + newData;
}else{
//add newData if undefined
content[index] = newData;
}

})
response.on('end', function(){
count++;
if (count === 3){
printResults();
}
})
})
}

for (var i = 0; i < 3; i++) {
httpGet(i);
}

关于javascript - learnyounode 练习 9 - 输出显示未定义、理解异步或逻辑的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42899518/

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