JavaScript中reduce方法的意外结果

时间:2017-02-24 20:20:31

标签: javascript reduce

我做了一个函数检查数字是否是素数,如果没有,则返回数字,否则(如果是素数)它返回0。

var maybePrimeNumber = [5, 8, 11, 14, 17, 20, 23, 28, 31]; //numbers to test

function isNotPrime(integer){
    var prime = true;            //start off assuming that it is a prime nr for now
    var returnNumber = 0;        //to be returned at the end

    for(i = 2; i<integer; i++){  //go from 2 up to the number,
        if(integer % i === 0){   //if the number is divisible by any nr between 2 and itself, 
            prime = false;       //then say that it isn't a prime number
        }
    }

    if(!prime){                  //if it isn't a prime number, then
        returnNumber = integer;  //prepare to send back the number
    }

    return returnNumber;
}

document.getElementById("demo").innerHTML = maybePrimeNumber.reduce(
    (total, integer) => {return total + isNotPrime(integer)}
); 
//sum all non-prime numbers up from the array and put the sum into the paragraph "demo"

问题如下:

当我跑这个时,它给了我75,但它应该给我70.

所以当我用这个替换最后一行时:

document.getElementById("demo").innerHTML = isNotPrime(maybePrimeNumber[0]);

要检查它是否错误地将5计算为非素数 - 它返回0,因此它不会计算错误。

为什么它给出75而不是70呢?

2 个答案:

答案 0 :(得分:5)

您应始终包含reduce的初始值。

document.getElementById("demo").innerHTML = maybePrimeNumber
  .reduce((total, integer) => {return total + isNotPrime(integer)}, 0);

total的第一个值是数组的第一个元素,如果没有包含初始值,那么5总是包含在总和中。

答案 1 :(得分:0)

以下功能有效且更清洁。请注意,命名约定会建议函数名isSomething返回一个布尔值。 (注意我使用了console.log,因为我在节点中测试了它。)

const maybePrimeNumber = [5, 8, 11, 14, 17, 20, 23, 28, 31]; //numbers to test
function isNotPrime(integer) {
  for(i = 2; i < integer / 2; i++){ //go from 2 up to the number,
    if(integer % i === 0){    //if the number is divisible by any nr between 2 and itself, 
      return true;          //then say that it isn't a prime number
    }
  }

  return false;
}

console.log(maybePrimeNumber.reduce((total, integer) => total + (isNotPrime(integer) ? integer : 0), 0));

正如@Xufox在他的回答中指出的,你的减少实际上是问题,因为你应该提供一个初始值(0)作为.reduce()的第二个参数;否则,数组中的第一个值被视为初始total值。