下面是一个在 JavaScript 中返回给定数字的质因数的函数。 我没有编写该函数,但一直在研究它以扩展我的编程知识。
我的问题是关于以下 if 语句中的 while 循环。
if(num % x){
x = 3;
while((num % x) && ((x = x+2) < root));
}
问题
- 如果后面没有代码,while 循环的目的是什么?
- 当 while 循环的计算结果为真时会发生什么?
- 当 while 循环的计算结果为 false 时会发生什么?
这是完整的功能。
function getPrimeFactors(num){
num = Math.floor(num);
var root = 0;
var factors = [];
var doLoop = 1 < num;
var x = 0;
while(doLoop){
root = Math.sqrt(num);
x = 2;
if(num % x){
x = 3;
while((num % x) && ((x = x+2) < root));
}
if(x > root){
x = num;
}else{
x = x;
}
factors.push(x);
doLoop = (x != num);
num = num/x;
}
return factors;
}
感谢帮助!!!
最佳答案
它真的在做这样的事情:
if(num % x){
x = 3;
while(num % x){
x = x + 2;
if(x < root)
continue;
else
break;
}
}
除此之外,将两个添加到x
就在有条件的情况下,所以不需要 body 。循环将执行到x < root
。或 num % x
不是真的。正文中没有任何说明。
这与执行 for 循环时发生的情况非常相似
for(int i=0; i < n; i++)
;
看到for循环体中没有任何指令,但是循环仍然会向i加一直到i >= n
.
关于javascript - if 语句中 while 循环的功能是什么? JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21714908/