2016-04-04 86 views
0
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」位,但我可能完全錯誤。有沒有人有任何想法?我的號碼檢查功能不起作用,爲什麼?

+0

爲什麼你使用數字作爲字符串?也許你想要:'if(toCheck.charCodeAt(i)<= 9 && toCheck.charCodeAt(i)> = 0){'? –

+0

@ PM77-1這是JavaScript,不是C,C++等。單引號和雙引號都是字符串。 –

+0

爲什麼不使用正則表達式:'if(toCheck.match(/ \ d /)!== null){..' – Andy

回答

1

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',雖然它在此處起作用,但您應該始終比較相同的類型。

in JS '9' == 9 is true while '9' === 9 is false

養成思考你正在處理的是什麼類型的習慣,這裏不會造成問題,但它會一路走下去!

+0

謝謝!完美工作! – ElementA

+0

沒有問題!請記住以上內容,歡迎來到SO! - 如果答案是你喜歡的,你可以選擇它作爲正確的答案,我們可以關閉 – JordanHendrix

0

也許你想要做

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

,並可以使用正則表達式

/[0-9]/.test(toCheck) 
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」。

+0

這個不起作用的問題,我剛剛嘗試'asdf4' – JordanHendrix

+0

抱歉,我的鏈接是錯誤的。 [鏈接](https://jsbin.com/guvuxukafa/edit?js,console)checkthis @Omarjmh – yongsup

相關問題