javascript - 为什么当我将第三个帖子插入数组时,此代码片段只显示 2 个帖子?

标签 javascript

我有两个功能。 第一个 (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 执行时,数组中只有两个 项,所以

  1. 遍历每一个
  2. 延迟显示它以供以后使用
  3. 停止

它永远不会在稍后检查数组是否有更多项,因为它已停止执行。

如果你确实想在 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/

相关文章:

javascript - 展开/折叠菜单表

javascript - 如何滚动流 JQuery UI 对话框

javascript - JS - 通过正则表达式将字符串拆分为子字符串

javascript - 简单的ajax发布未捕获的ReferenceError

javascript - 我的 javascript 包装器的多个实例

javascript - 点击事件未触发

javascript - 如何在 JS 文件中隐藏严肃的业务逻辑

javascript - 如何使用javascript转换日期格式

javascript - 从仅包含发送的查询的数组中排除结果。 MongoDB

javascript - 如何扩展 JqPlot 类并添加我自己的原型(prototype)函数