简体   繁体   中英

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. My function (below) works as I want it to with the exception that it returns 'undefined' at the end of the log. 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).

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()); with just Yeah(); . Your function returns undefined since it has no return statements.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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