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」位,但我可能完全錯誤。有沒有人有任何想法?我的號碼檢查功能不起作用,爲什麼?
爲什麼你使用數字作爲字符串?也許你想要:'if(toCheck.charCodeAt(i)<= 9 && toCheck.charCodeAt(i)> = 0){'? –
@ PM77-1這是JavaScript,不是C,C++等。單引號和雙引號都是字符串。 –
爲什麼不使用正則表達式:'if(toCheck.match(/ \ d /)!== null){..' – Andy