我有两个功能。
第一个 (getPosts
) 访问一组对象(称为 posts
)并在延迟一段时间后使用 setTimeout 在网页上“显示”它们。
第二个 (createPost
) 将一个对象作为参数(post
)并将其推送到 posts 数组的末尾。
代码如下:
const posts = [
{title: "#1", body: "This is post number one"},
{title: "#2", body: "This is another post (#2)"}
]
function getPosts(){
posts.forEach((post,index,arr)=>{
setTimeout(()=>{
document.body.innerHTML += post.body+'<br>';
},3000);
})
}
function createPost(post){
posts.push(post);
}
getPosts();
//third post added here but does not show?
createPost({title:'henlo',body:'troll message'});
我的问题是,为什么 getPosts 在 3 秒后执行,但没有在网页上显示第三个帖子?
提前致谢。
最佳答案
展示它的最简单方法是展示 getPosts
用一个小的 console.log
实际做了什么:
const posts = [
{title: "#1", body: "This is post number one"},
{title: "#2", body: "This is another post (#2)"}
]
function getPosts(){
posts.forEach((post,index,arr)=>{
console.log(`item ${index} with content "${post.body}". Showing delayed for later.`)
setTimeout(()=>{
document.body.innerHTML += post.body+'<br>';
},3000);
})
}
function createPost(post){
posts.push(post);
}
getPosts();
//third post added here but does not show?
createPost({title:'henlo',body:'troll message'});
在您的getPosts
执行时,数组中只有两个 项,所以
- 遍历每一个
- 延迟显示它以供以后使用
- 停止
它永远不会在稍后检查数组是否有更多项,因为它已停止执行。
如果你确实想在 3 秒后打印所有内容,那么你可以将整个主体包裹在 setTimeout
中:
const posts = [
{title: "#1", body: "This is post number one"},
{title: "#2", body: "This is another post (#2)"}
]
function getPosts(){
setTimeout(()=>{//<-- delay the entire function body
posts.forEach((post,index,arr)=>{
document.body.innerHTML += post.body+'<br>';
})
},3000);//<--
}
function createPost(post){
posts.push(post);
}
getPosts();
//third post added and shown later
createPost({title:'henlo',body:'troll message'});
或者更简单的只是延迟执行,而不是在函数中包含该逻辑:
const posts = [
{title: "#1", body: "This is post number one"},
{title: "#2", body: "This is another post (#2)"}
]
function getPosts(){
posts.forEach((post,index,arr)=>{
document.body.innerHTML += post.body+'<br>';
})
}
function createPost(post){
posts.push(post);
}
setTimeout(getPosts, 3000); //delay here
createPost({title:'henlo',body:'troll message'});
关于javascript - 为什么当我将第三个帖子插入数组时,此代码片段只显示 2 个帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58268270/