我正在尝试将值推入数组,然后如果该数组仅包含两个值,则将其声明为素数。由于某些原因,for循环似乎没有向该数组发送任何值...
function primeOrNot() {
var input = parseInt(prompt('Please, give me a number'));
var list = [];
list.push(1);
list.push(input);
for (var i = 2; i < input / 2; i++) {
if (Math.floor(input / i) == input / i) {
list.push(i);
}
if (list.length == 2) {
alert('The number you chose is a prime number.');
} else 'The number you chose is not a prime number. You lose.';
}
console.log(list);
}
primeOrNot();
答案 0 :(得分:0)
您在}
中缺少结尾else
。这有效:
function primeOrNot() {
var input = parseInt(prompt("Please, give me a number"));
var list = [];
list.push(1);
list.push(input);
for(var i=2; i<input/2; i++){
if (Math.floor(input/i) == input/i) list.push(i);
}
if(list.length == 2){
alert("The number you chose is a prime number.");
} else alert("The number you chose is not a prime number. You lose.")
console.log(list);
}
primeOrNot();