我的网络服务器上有一个目录,我在其中上传 timestamp.md 文件以发布到我网站上的“博客”-div。使用 javascript 通过 scandir() (PHP) 获取 dir 的索引返回:
["2018-12-05T13:28:10.000Z.md","2018-12-05T12:58:19.858Z.md","2018-12-05T12:37:25.012Z.md","2018-12-05T12:28:52.612Z.md","..","."]
我将 obve 存储在 var"file"中。
然后,我执行一个 for 循环,从 index.html 中获取,以获取所有时间戳的内容。mds
(我创建一个空数组来存储 md-content)
var mdcontent = new Array()
for(var i=0;i<files.length -2;i++) {
fetch('md/'+files[i])
.then( response => response.text())
.then(result => mdcontent.push(result));
}
console.log(mdcontent) returns what looks like a normal array
consol.log(mdcontent[0]) (or any other element of array) returns undefined.
console.log(mdcontent.lenght) returns 0.
问题是如何访问这个数组的元素?
我不知道这次我错在哪里,如果有人可以帮助我,我将不胜感激!
提前致谢
最佳答案
当您使用fetch
时,它会返回Promise
,它表示异步操作。您不应该像您那样访问 mdcontent
的元素 - 使用同步代码可以,但在这里不行。相反,您需要等待每个 Promise(每个 fetch
+ .text()
)完成。您可以使用Promise.all
来做到这一点.
var promises = new Array();
for (var i=0; i < files.length - 2; i++) {
promises.push(
fetch('md/' + files[i])
.then(res => res.text())
);
}
Promise.all(promises).then(mdcontent => {
console.log(mdcontent);
console.log(mdcontent.length);
console.log(mdcontent[0]);
});
我建议您阅读有关异步 JavaScript 的内容。也许this article 。当您不了解 Promise 的异步性质时,可能很难使用它。您可能还想使用asynchronous functions和 await
而不是 .then(...)
。
关于javascript - array.push 后数组元素未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53646803/