JavaScript 函数未检索数组元素

JavaScript function not retrieving array elements

我有一个元素数组(我将在下面显示一个片段),具有不同级别的数组元素,我想要一个特定的函数来检索特定级别的数组元素并呈现它们在 table 中,我最初的两个函数可以无缝运行,但是在复制我之前的函数并更改适当的变量命名和引用后,第二个函数无法成功地将数组元素显示到屏幕上。

我一直在寻找可能的错误引用或次要遗漏的元素,但我不知所措。

这是我的变量数组:

{title: "Basketball Topics", followers: 122, articles: 4, posts: [
    {postId: 106, contents: "data", author: "data", replies:[
        {replyId: 16, comment: "data", comment_author: "data"},
        {replyId: 17, comment: "data", comment_author: "data"},
        {replyId: 18, comment: "data", comment_author: "data"}
    ]},
]}

这里有一些非常简单的 table onClick 事件函数,用于显示适当的页面

function topicOnClick (node, topic){
    'use strict';
    node.on("click", function() {
        showSingleTopic(topic);
    });
}

function threadOnClick (node, topic){
    'use strict';
    node.on("click", function() {

        showComments(topic);
    });
}

这是我的数组引用函数:

function getSingleTopic(someTopics, topicTitle) {
    return someTopics.find(function (topic) {
        return topic.title === topicTitle;
    });    
}

function getSingleComment(someTopics, topicTitle) {
    return someTopics.find(function (topic) {
        return topic.contents === topicTitle;
    });    

}

以下是尝试通过 table 元素将数组元素呈现到屏幕的循环:

function showSingleTopic (topicDetails){

    'use strict';

    var page = $("#individualForumPage");

    var individualTopicTable = $("<table class='forumTable'><tr><th>Contents</th><th>Author</th></tr></table>");



        for (index in topicDetails.posts) {

                        var post = topicDetails.posts[index]; 
        var row = $("<tr></tr>");
        row.append("<td>" + post.contents + "</td>");
        row.append("<td>" + post.author + "</td>");

        threadOnClick(row, topics[index]);
        individualTopicTable.append(row);

        }
    page.html(individualTopicTable);
}

这里是不显示在屏幕上的重复函数(也不检索数组元素):

function showComments (commentDetails){

    'use strict';

    var page = $("#commentsPage");


    var commentTable = $("<table class='forumTable'><tr><th>Author</th><th>Comments</th></tr></table>");



        for (index in commentDetails.replies) {

                        var reply = commentDetails.replies[index]; 

        var row = $("<tr></tr>");
        row.append("<td>" + reply.comment_author + "</td>");
        row.append("<td>" + reply.comment + "</td>");

        commentTable.append(row);

        }

page.html(commentTable);


}

在您的 showSingleTopic 中,您传递给点击处理程序的值似乎不正确。你有:

threadOnClick(row, topics[index]);
individualTopicTable.append(row);

不过大概应该是:

threadOnClick(row, post);
individualTopicTable.append(row);

您已经引用的 post 具有在 showComments() 中引用的子键 'details'。您的原始代码将索引应用到与最初派生的数组不同的数组。