Javascript 函数未显示正确的结果
我有一个我已经编程的因子查找器,它应该首先检查输入框中输入的值是1还是0,这样它会显示“1的因子是1.”或“0的因子是0.”,但当我将数字0输入输入框时,它会显示“0的因子是”。但我不明白为什么。这可能是一个我无法理解的简单错误。这是我的密码。 HTML:Javascript 函数未显示正确的结果,javascript,html,arrays,primes,factors,Javascript,Html,Arrays,Primes,Factors,我有一个我已经编程的因子查找器,它应该首先检查输入框中输入的值是1还是0,这样它会显示“1的因子是1.”或“0的因子是0.”,但当我将数字0输入输入框时,它会显示“0的因子是”。但我不明白为什么。这可能是一个我无法理解的简单错误。这是我的密码。 HTML: JavaScript 因子查找器 输入一个数字以查找系数 编号: 结果 JavaScript: //counters var numbernum = 0; var numinput = 1; //function function fi
JavaScript
因子查找器
输入一个数字以查找系数
编号:
结果
JavaScript:
//counters
var numbernum = 0;
var numinput = 1;
//function
function findFactor(){
var array = new Array();
//get input
thenumber=document.prime.primeinput.value;
//special circumstances for 1 and 0
if (thenumber == 1 || thenumber == 0){
amount = "The factor of ";
verb = " is ";
} else{
amount = "The factors of ";
verb = " are ";
}
//factor finder
for (i=1; i<thenumber + 1; i++){
//check to see if the number is a factor
if(thenumber % i == 0){
//check if the number is 1 or 0 to state the factors are 1 or 0
//not working with 0
if(thenumber == 1 || thenumber == 0){
if (thenumber == 1){
array[0] = 1;
} else if (thenumber == 0){
array[0] = 0;
}
//if the number isn't 0 or 1
} else if(thenumber != 1 && thenumber != 0){
if (thenumber == numinput){
array[numbernum] = "and " + numinput;
} else{
array[numbernum] = numinput;
numbernum ++
}
}
}
numinput ++
}
//append to the HTML
var make = document.createElement("p");
var apply = document.createTextNode(amount + thenumber + verb + array.join(", ") + ".");
make.appendChild(apply);
document.getElementById("here").appendChild(make);
//reset counters and clear array
numbernum = 0;
numinput = 1;
var array = 0;
}
//计数器
var numbernum=0;
var numinput=1;
//作用
函数findFactor(){
var数组=新数组();
//获取输入
编号=document.prime.primeinput.value;
//1和0的特殊情况
如果(数字=1 | |数字=0){
amount=“成本系数”;
动词=“是”;
}否则{
amount=“的因素”;
动词=“是”;
}
//因子查找器
for(i=1;ifor不循环,因为:
对于(i=1;i0+1
尝试将此更改为
对于(i=1;i在0
和1
的特殊情况下,不要麻烦使用for
循环,因为您知道正确的结果应该是什么。因此将if
放在for
之外:
if (thenumber < 2) {
array[0] = thenumber;
} else {
for (var i = 1; i <= thenumber; i++) {
if (thenumber % i == 0) {
array.push(i);
}
}
}
if(编号<2){
数组[0]=编号;
}否则{
对于(var i=1;i如果thenumber
为0
,则循环立即终止,因为1
为false。另外,如果(thenumber!=1&&thenumber!=0),则不需要
,只需使用else
。这与if
条件正好相反,只有当if
为false时,才会执行else
。
if (thenumber < 2) {
array[0] = thenumber;
} else {
for (var i = 1; i <= thenumber; i++) {
if (thenumber % i == 0) {
array.push(i);
}
}
}