简体   繁体   English

首次使用后,JavaScript函数的参数变为未定义

[英]JavaScript function's argument becomes undefined after the first use

I finally came up with code, which gets jSON data from file and now I'm trying to make some functions for that. 我终于想出了代码,该代码从文件中获取jSON数据,现在我正试图为此做一些功能。 Take a look at the code: 看一下代码:

var comments = [];

function printComment(comment) {

var $comment_div = "<div class='comment'><p class='comment-text'>"+comment.comment_body+"</p><img class='comment-photo' src='"+comment.comment_url+"'/><a rel='"+comment.comment_from+"' class='name' href='"+comment.comment_url+"'>"+comment.comment_user+" via <i class='fa'></i></a></div>";

$($comment_div).appendTo('#comments-content');

};

var i = 0

$(function() {

$.getJSON("js/comments.js", function(data) {

    comments = data.comments;

    for(i; i < 3; i++ ) {

        printComment(comments[i]);
        console.log(i);

    }

    setInterval(function() {

        if ( i > comments.length ) {

            i = 0;

        } else {

            i++;
            printComment(comments[i]);
        }

        console.log(i);

    }, 5000);  

});

});

Problem is that the globally defined function triggers in the "for" loop with no problem, but in function in setInterval console returns "comment (which is argument of function printComment) is undefined". 问题是全局定义的函数在“ for”循环中触发没有问题,但在setInterval控制台的函数中返回“注释(这是函数printComment的参数)未定义”。 Could you direct me or just answer what I'm doing wrong? 您能指导我还是只回答我做错了什么?

Cheers! 干杯!

I believe the problem is that your if condition resets i only if i > comments.length , however, if i == comments.length (or even i == comment.length - 1 ) then your code in the else block will try to access items beyond the bounds of the array. 我相信问题是,仅当i > comments.length ,您的if条件才会重置i ,但是,如果i == comments.length (甚至i == comment.length - 1 ),则您在else块中的代码将尝试访问超出数组范围的项目。 I think you're looking for something like this: 我认为您正在寻找这样的东西:

setInterval(function() {
    if ( i >= comments.length ) {
        i = 0;
    }

    printComment(comments[i++]);
}, 5000);

Although your code is very confusing. 虽然您的代码非常混乱。 It's hard to tell exactly what you're trying to accomplish here. 很难确切地说明您要在此处完成的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM