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

时间:2016-04-04 01:58:34

标签: 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循环中的&lt; =“9”位,但我可能完全错了。有没有人有任何想法?

3 个答案:

答案 0 :(得分:1)

Working JsBin

不是&#39;&lt; =&#34; 9&#34;&#39;

您需要访问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();

现在,正如其他评论者提到的那样,你试图看一个数字是否比另一个更大,但是你正在比较字符串:

让我们说通过&#39; asdf5&#39;。然后你就孤立了&#39; 5&#39;在循环中并将其与另一个字符串'5' <= '9'进行比较,虽然它在这里工作,但您应该始终比较相同的类型。

JS '9' == 9中的

true'9' === 9false

养成思考你正在处理什么类型的习惯,它不会在这里造成问题,但它会在未来发展!

答案 1 :(得分:0)

也许你想做

if (toCheck.charCodeAt(i) <= "9".charCodeAt(0) && toCheck.charCodeAt(i) >= "0".charCodeAt(0)) {

,您可以使用RegExp

/[0-9]/.test(toCheck)

答案 2 :(得分:0)

jsbin

试试这个!

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++) {
              console.log(toCheck.charCodeAt(i));
                if (toCheck.charCodeAt(i) <= "9".charCodeAt(0) && toCheck.charCodeAt(i) >= "0".charCodeAt(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();

如果你想与UNICODE比较,你也必须改变UNICODE“0”和“9”。