【发布时间】:2017-10-04 18:06:15
【问题描述】:
我正在尝试使用 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>
【问题讨论】:
-
您不会对
palindrome的初始调用的返回值做任何事情——您应该将其重命名为isPalindrome。您是否打算将输入视为字符串? (因为有一种算法解决方案可以检查整数是否是回文而不将其转换为字符串)。 -
更新好吧,我觉得自己很愚蠢!原来我有一些拼写错误;这就是我在凌晨 2:30 尝试编写代码时得到的结果!我仍然无法检查以确保它是整数而不是其他任何东西。我似乎无法找出正确的语法来排除除数字之外的所有内容。
-
我收到一个非常奇怪的错误!当我输入 123456 或 5 位以外的任何其他序列号时,它会崩溃。这是怎么回事?
-
原来我找到的解决方案导致了错误! isNan(num) 函数显然不喜欢像 1234 或 7654 这样的顺序输入。(注意!)我改用 === 检查器;这是一个简单的交换。我有点自己解决了,但感谢指点!如果有人对我的想法感兴趣,请告诉我,我会发布。
标签: javascript html function palindrome