[英]Javascript for summing primes crashing
I have the following exercise code where I'm trying to calculate the sum of all the primes from 1-10 which is crashing due to recursion. 我有以下练习代码,在这里我试图计算由于递归而崩溃的1-10之间的所有质数之和。
I'm having trouble with my for and while loops as the code doesn't seem to be cycling through my var i , and is getting stuck on the initial assignment of i = 3 . 我的for和while循环遇到麻烦,因为代码似乎没有遍历我的var i ,并且卡在了i = 3的初始赋值上。
I'm not looking for the correct answer or the most efficient answer yet but I am looking for someone to help me understand what's wrong. 我没有在寻找正确的答案或最有效的答案,但我正在寻找可以帮助我了解问题所在的人。
Here's the code: 这是代码:
var array = [2];
var total = 0;
var j = 0;
function isPrime(i, j) {
if ( i%array[j] === 0 ) {
console.log("i was " + i + " and j was " + j);
console.log(i + " is not a prime");
j = array.length;
}
else if ((j + 1) === array.length) {
console.log(i + " is a prime");
total += i;
console.log("total so far is " + total);
array.push(i);
console.log(array);
j = array.length;
console.log(j);
}
else {
j++;
isPrime(i,j);
}
}
for(var i = 3; i <=10; i++) {
while(j < array.length) {
console.log("i is " + i + " and j is " +j);
isPrime(i, j);
}
}
console.log(total);
console.log(array);
var j = 0;
function isPrime(i, j) { …
means that you have two distinct j
variables: One outside the function, and one inside that shadows the other. 表示您有两个不同的j
变量:一个在函数外部,一个在阴影内。 From inside you never will be able to assign or read the outer variable. 从内部开始,您将永远无法分配或读取外部变量。 Therefore, the outer j
stays 0
forever and while (j < array.length)
will loop infinitely. 因此,外部j
永远保持0
, while (j < array.length)
将无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.