我正在尝试并且未能使用javascript检查5位整数是否是回文。我已经得到了正确检查5位数字符串的代码(还没有整数)。那部分应该比较容易弄明白。
我的主要问题:我在javascript中使用函数的结构吗?如果是这样,我怎样才能使函数调用正常工作?它只是在收到所需的输入后退出程序。
代码如下:
<script type="text/javascript">
var userInput;
var counter = 0;
function palindrome(userInput) {
var re = /[^A-Za-z0-9]/g;
userInput = userInput.toLowerCase().replace(re, '');
var len = userInput.length;
for (var i = 0; i < len/2; i++) {
if (userInput[i] !== userInput[len - 1 - i]) {
return false;
}
}
return true;
}
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
while (counter < 10){
if (userInput.length == 5){
if (pandindrome(userInput) == true){
document.write("The input is a palindrome!");
}
else if (pandindrome(userInput) == false){
document.write("The input is not a palindrome! Try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
}
counter++;
}
else if (userInput.length != 5){
alert("The input you entered was not 5-digits! Please try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
}
}
</script>
答案 0 :(得分:0)
我已经测试了你的代码,一切正常!
FIY,我设置一个变量isPalindrome来存储函数回文的返回值。然后你可以直接在if语句中使用它,而不是比较为true。
var userInput;
var counter = 0;
function palindrome(userInput) {
var re = /[^A-Za-z0-9]/g;
userInput = userInput.toLowerCase().replace(re, "");
var len = userInput.length;
for (var i = 0; i < len / 2; i++) {
if (userInput[i] !== userInput[len - 1 - i]) {
return false;
}
}
return true;
}
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
var isPalindrome = palindrome(userInput);
while (counter < 10) {
if (userInput.length == 5) {
if (isPalindrome) {
document.write("The input is a palindrome!");
} else {
document.write("The input is not a palindrome! Try again!");
userInput = window.prompt(
"Please enter a 5-digit, numerical palindrome: "
);
isPalindrome = palindrome(userInput);
}
counter++;
} else if (userInput.length != 5) {
alert("The input you entered was not 5-digits! Please try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
isPalindrome = palindrome(userInput);
}
}