我正在尝试过滤一组随机数以提取素数。
我有一个工作函数 (isPrime
) 似乎正确返回 true
或 false
但数组中的每个数字都被“过滤” "到过滤器返回的数组中。
我查看了过滤器的文档并观看了一些视频,但我没有弄清楚,我认为这可能与过滤器内部的函数调用有关。你能告诉我我的错误在哪里吗?
numArray = [];
for(i=0; i<1000; i++){
numArray.push(Math.random(1000));
}
const isPrime = (num) => {
for(i=2;i<num;i++){
if(num % i === 0){
return false;
}
}
return true;
}
const results = numArray.filter(value => isPrime(value));
for(num in results){
console.log(num);
console.log(isPrime(num)) //added to demonstrate function is working and should return false to the filter
}
您以错误的方式生成随机数。您的代码只会创建一个小于 1
的 float 组,因此根据您的 isPrime
,它们都将是质数。
注意:不要在没有let
或cosnt
的情况下使用变量,这会导致代码出现很多问题。
如何生成随机数?
Math.random()
是返回 0
和 1
之间的 float 的函数。
- 将该数字乘以您想要的最大射程。
- 相乘后仍然是一个 float 。所以使用
Math.floor()
将随机 float 舍入为整数
let numArray = [];
for(let i=0; i<10; i++){
numArray.push(Math.floor(Math.random() * 30));
}
const isPrime = (num) => {
for(let i=2;i<num;i++){
if(num % i === 0){
return false;
}
}
return true;
}
const results = numArray.filter(value => isPrime(value));
console.log(JSON.stringify(numArray))
console.log(JSON.stringify(results));
回答OP的问题
"Why bottom for loop used to check the code gives numbers 5, 6 ... 997, 998"
在 javascript 中,数组基本上是对象。 for..in
是一个循环,它迭代对象的 keys 而不是值。因此,如果数组键是数组的索引,在上述情况下为 0...999
。所以它正在记录那些索引