简体   繁体   English

在Javascript中运行函数,但最后总是返回“ undefined”

[英]Running a function in Javascript but it keeps returning 'undefined' at the end

I am quite new to javascript so please excuse if this is a really stupid easy thing to fix and I have missed something minor. 我对javascript很陌生,因此,如果这是一件非常愚蠢的容易修复的事情,而我错过了一些小事情,请原谅。 My function (below) works as I want it to with the exception that it returns 'undefined' at the end of the log. 我的函数(如下)按我的意愿工作,但它在日志末尾返回“ undefined”。 I have looked through a few other posts that have had their problem rooted in an undefined variable or poor syntax but from what I understood from those that's not my problem (but I'm new so maybe I just didn't understand). 我浏览了其他一些帖子,这些帖子的问题源于未定义的变量或语法不正确,但是从我的理解中可以发现,这不是我的问题(但我是新手,所以也许我只是不明白)。

The function should log each value divisible by 4 except values divisible by 100 (with the exception of values divisible by 400, they are still logged). 该函数应记录每个可被4整除的值,但可被100整除的值(除了可被400整除的值,它们仍将被记录)。

function Yeah(date){
    var today = new Date().getFullYear();
    if (today % 4 == 0) {
    console.log('This year is a leap year');
}
for(x = today; x > 0; x--){
        if(x % 400 == 0){
        console.log('MEGA leap year' +' '+ x +'!');
    }
    else {
            if (x % 100 == 0) {
                continue;
    }
    else {
                if (x % 4 == 0) {
                    console.log('Leap year' + ' ' + x + '!');
            }
        }
    }
}
}
console.log(Yeah());

Replace console.log(Yeah()); 替换console.log(Yeah()); with just Yeah(); 只需Yeah(); . Your function returns undefined since it has no return statements. 您的函数返回undefined因为它没有return语句。

You said it works the way you want already, so I assume you don't need it to return anything. 您说它已经按照您想要的方式工作,所以我假设您不需要它来返回任何东西。 In which case you definitely don't need to log its return value. 在这种情况下,您绝对不需要记录其返回值。

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

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