function showPrimes(n) { for (let i = 2; i < n; i++) { if (!isPrime(i)) continue; console.log(i); // a prime } } function isPrime(n) { for (let i = 2; i < n; i++) { if ( n % i == 0) return false; } return true; } document.getElementById("res").innerHTML = showPrimes(5);
<div id='res'></div>
How to show all showprimes value into the div element it return undefined when using above code
It shows undefined because showPrimes
doesn't return anything, so calling it results in the value undefined
. If you want it to return something, return something (perhaps an array); then that will get assigned to innerHTML
(after being converted to string). See ***
comments:
function showPrimes(n) { const primes = []; // *** for (let i = 2; i < n; i++) { if (!isPrime(i)) continue; console.log(i); primes.push(i); // *** } return primes; // *** } function isPrime(n) { for (let i = 2; i < n; i++) { if ( n % i == 0) return false; } return true; } document.getElementById("res").innerHTML = showPrimes(5);
<div id="res"></div>
That uses the default conversion of array to string, which calls Array#join
, which uses a comma between the values. You could call join
explicitly to do something else, or any of several other tweaks.
There is small issue in your code:
showPrimes
function that can be actually assigned in document.getElementById("res").innerHTML
. showPrimes
function then it will not give you the next prime number as showPrimes
function will get terminated. So, the solution would be to store the prime numbers in an array and then return this array when no prime numbers are left to generate. var primeArray = []; function showPrimes(n) { for (let i = 2; i < n; i++) { if (!isPrime(i)) continue; console.log(i); // a prime primeArray.push(i); } return primeArray; } function isPrime(n) { for (let i = 2; i < n; i++) { if ( n % i == 0) return false; } return true; } document.getElementById("res").innerHTML = showPrimes(5);
<div id='res'></div>
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.