javascript - 我的号码查询功能不起作用,为什么?

标签 javascript function for-loop

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"位,但我可能完全错了。有人有什么想法吗?

最佳答案

Working JsBin

这不是 '<= "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' == 9true'9' === 9false

养成思考您正在处理的类型的习惯,它不会在这里造成问题,但它会在未来产生问题!

关于javascript - 我的号码查询功能不起作用,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393530/

相关文章:

c - 在什么情况下会在 for 循环终止条件中使用位移运算符?

php - 在文件中查找一个单词,然后将接下来的 10 个值放入数组中

r - 将一个单元格中的多个值分成多个单元格

javascript - 试图避免重复,简化...创建全局变量并简化我的 javascript -- 纯 js 没有 jquery

c# - 检查 DateTime 是否大于另一个 DateTime 的正确方法

javascript - HTML如何编辑视频的布局

excel - 在一组单元格中查找单词

javascript - 按钮 onclick 调用 javascript 函数不起作用

javascript - D3 : Combine two colour scales into one

javascript - 每天在 5 :00 AM using firebase javascript 清除 firebase 数据库值