我想从数组中删除非素数,以下仅删除偶数而不是素数。

function sumPrimes(num) {
  //Produce an array containing all number of to and including num
  let numArray = [];
  for (let i = 1; i <= num; i++) {
    numArray.push(i);
  }

  //Remove non-prime numbers from the array
  numArray.map((number) => {
    for (let i = 2; i < number; i++) {
        if(number % i === 0) {
            let index = numArray.indexOf(number);
            return numArray.splice(index, 1);
        }
    }
  });

 return numArray;

}

sumPrimes(10);


当前正在返回:

[1, 2, 3, 5, 7, 9]


但是,质数为1、2、3、5、7(不包括9);

最佳答案

使用filter()代替:



var numArray = [2, 3, 4, 5, 6, 7, 8, 9, 10]

numArray = numArray.filter((number) => {
  for (var i = 2; i <= Math.sqrt(number); i++) {
    if (number % i === 0) return false;
  }
  return true;
});

console.log(numArray);

10-06 12:24