My attempt at creating a Javascript code to check for prime numbers using an array has hit a roadblock:
var primes = [2];
function verify(x)
{
var i;
var x;
var k;
//for (k in primes)
for (k=0; k<primes.length; k++)
{
if (primes[k] == x)
return true;
else if (x%primes[k] == 0)
return false;
}
for (i=k+1; i<x; i++)
{
if (x%i == 0)
return false;
}
primes.push(x);
return true;
}
The issue I am facing is:
If I use
for (k=0; k<primes.length; k++)
the for loop works correctly, but when I use
for (k in primes)
it doesn't work.
It seems that after each primes.push(x)
, the number of elements in the object 'primes' is always zero.
Perhaps it's a simple mistake, but I can't seem to locate it! Thank you for your assistance!