This question already has answers here:
Generating random whole numbers in JavaScript in a specific range?

(34个答案)


9个月前关闭。




我正在尝试过滤随机数数组以提取素数。

我有一个工作函数(isPrime),似乎可以正确返回truefalse,但是数组中的每个数字都被“过滤”到过滤器返回的数组中。

我查看了过滤器的文档并观看了一些视频,但我还没有弄清楚,我认为这可能与过滤器内部的函数调用有关。你能告诉我我的错误在哪里吗?

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的浮点数组,因此根据isPrime,它们都是素数。
注意:请勿在没有letcosnt的情况下使用变量,否则会导致代码中出现许多问题。
如何创建随机数?

  • Math.random()是返回01之间的浮点数的函数。
  • 您可以将该数字乘以想要的最大范围。
  • 相乘后仍然是一个浮点数。因此,使用Math.floor()将随机浮点数舍入为整数

  • 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的问题

    在javascript数组中,基本上是对象。 for..in是一个循环,它循环访问对象的而不是值。因此,在上述情况下,如果数组键是数组的索引,则为0...999。所以它正在记录这些索引

    07-28 03:59
    查看更多