简体   繁体   中英

First 100 primes javascript, why do I get undefined after my array of primes?

I get the 100 primes printed, but I also get undefined at the end. Why would that be?

function HundoPrimeNumbers() {
    var primes = [];

    function isPrime(n) {
        if (isNaN(n) || !isFinite(n) || n % 1 || n < 2) return false;
        var m = Math.sqrt(n);
        for (var i = 2; i <= m; i++) if (n % i == 0) return false;
        primes.push(n);
    }

    var n = 0
    while (primes.length < 100) {
        isPrime(n);
        n++;
    }
    console.log(primes.join());
}

console.log(HundoPrimeNumbers());

You are logging the result of HundoPrimeNumbers :

console.log(HundoPrimeNumbers()); 

HundoPrimeNumbers does not have a return statement. When a function doesn't have a return statement, or returns without a value, like return; , it actually ends up returning undefined . This then gets logged to the console.

Solution: call it like this:

HundoPrimeNumbers();

undefined是console.log()的返回值

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