当没有那么大的时候使用nodejs处理内存不足错误

Process out of memory error using nodejs when nothing should be that large

确切的错误是 "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory" 程序应该在第 n 个位置得到素数,但无论这个数有多小都会失败。这个错误到底是什么意思,我该如何解决?

var primes = [2, 3, 5];
var x = 0;
var y = 0;
var z = 6;
var nthPrime = function(number){
    while (primes.length <= number){
        y = 0;
        while (y <= primes.length){
            x = primes[y];
            if (z % x === 0){
                y++;
            } else{
                primes.push(z);
                z++;
            }
        }
    }
    console.log(primes[number]);
};
nthPrime(3);

第二个while循环是一个无限循环。在前两次迭代之后,else 语句比 if 语句发生得更频繁。这意味着 primes 数组的长度增加速度快于 y 值。进一步研究逻辑,这个特定错误应该会自行解决。