为什么javascript's . touppercase函数包含数字?

Why does the javascript's .toUpperCase function include numbers?

本文关键字:函数 包含 数字 touppercase javascript 为什么      更新时间:2023-09-26

当我在"password"中输入数字时,没有大写错误消息。帮助! !您可以忽略大部分代码。我的问题是,为什么当我在密码中输入数字时,控制台不会记录"密码不正确"。请用大写字母。"(输入密码的位置在代码的最后一行)谢谢你的帮助!

var specialCharacters = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", 
"[", "]"];
function isPasswordValid(input) {
if (hasUpperCase(input) && hasLowercase(input) && isLongEnough(input) &&  hasSpecialCharacter(input)) {
console.log("The password is valid.");
}
if (!hasUpperCase(input)) {
console.log("Incorrect password. Please put a uppercase letter.");
}
if (!hasLowercase(input)) {
console.log("Incorrect password. Please put a lowercase letter.");
}
if (!isLongEnough(input)) {
console.log("Incorrect password. Please increase the length of your password to 8 characters.");
}
if (!hasSpecialCharacter(input)) {
console.log("Incorrect password. Please put a special character.");
}
}
function hasUpperCase(input) {
for (var i = 0; i < input.length; i++) {
if (input[i] === input[i].toUpperCase()) {
  return true;
}
}
}
function hasLowercase(input) {
for (var i = 0; i < input.length; i++) {
if (input[i] === input[i].toLowerCase()) {
  return true;
}
}
}
function isLongEnough(input) {
if (input.length >= 8) {
return true;
}
}
function hasSpecialCharacter(input) {
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < specialCharacters.length; j++) {
  if (input[i] === specialCharacters[j]) {
    return true;
  }
}
}
}
isPasswordValid("");

您的输入是一个字符串。如果您对它使用toUpperCase()方法,它将忽略数字,并将小写字母/字符转换为大写字母/字符。

"there is no uppercase error message"因为您没有检查大写字母,您只是在测试字符串是否相等。

"1" == "1".toUpperCase()

toUpperCase()不去掉数字或其他非字母字符。

如果你想测试一个大写字母,实际上测试一个大写字母。

您可以使用正则表达式测试来完成:

if( !(/[A-Z]/).test(input[i]) ){
    //No uppercase letters found
}

[A-Z]告诉表达式在提供的字符集(在本例中是大写a到大写Z)中查找一个字符

尝试为if语句添加更多的if参数,像这样()

function hasUpperCase(input) {
  for (var i = 0; i < input.length; i++) {
    if (input[i] === input[i].toUpperCase() && isNaN(parseInt(input[i]))) {
      return true;
    }
  }
}