function numbCheck() {
// Declaring variables
var toCheck = prompt("Enter a string!");
var numbCount = 0;
// For loop to cycle through toCheck and look for numbers
for (i = 0; i <= toCheck.length; i++) {
if (toCheck.charCodeAt(i) <= "9" && toCheck.charCodeAt(i) >= "0") {
numbCount++;
}
}
// If a number is found numbCount should be > 0 and the alert will go off
if (numbCount > 0) {
alert("You can't have a number in your name!");
}
}
numbCheck();
我认为问题出在 for 循环中的 <= "9"位,但我可能完全错了。有人有什么想法吗?
最佳答案
这不是 '<= "9"'
您需要访问 toCheck
中的索引像这样:
toCheck[i]
:
function numbCheck() {
// Declaring variables
var toCheck = prompt("Enter a string!");
var numbCount = 0;
// For loop to cycle through toCheck and look for numbers
for (i = 0; i <= toCheck.length; i++) {
if (toCheck[i] <= "9" && toCheck[i] >= "0") {
numbCount++;
}
}
// If a number is found numbCount should be > 0 and the alert will go off
if (numbCount > 0) {
alert("You can't have a number in your name!");
}
}
numbCheck();
现在,正如其他评论者所提到的,您正在尝试查看一个数字是否大于另一个数字,但您正在比较字符串:
假设我们通过了“asdf5”。然后,您在循环中隔离“5”并将其与另一个字符串进行比较: '5' <= '9'
,虽然它在这里有效,但您应该始终比较相同的类型。
JS '9' == 9
是 true
而'9' === 9
是 false
。
养成思考您正在处理的类型的习惯,它不会在这里造成问题,但它会在未来产生问题!
关于javascript - 我的号码查询功能不起作用,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393530/