用户的详细年龄检查

时间:2020-09-06 11:09:39

标签: javascript html

/ *我要检查用户的年龄,如果 18岁或以上,则授予访问权限。如果没有,请继续进行下一个步骤,询问他们是否得到父母的许可。如果(是||是||是)授予访问权限。如果(否||否||否)拒绝访问。如果除(是和否)以外的其他内容,请返回(输入错误!)。如果(!是和!否“即用户取消了”)返回(下次尝试!) * /

let age = prompt('How old are you?', [18]);
    
function ageChecker(age) {
  if (age >= 18) {
      return 'Access Granted!';
  } 
  else if (!age) {
      return 'Sorry Enter Your Age!';    
  }
  else {
    let confirmation = prompt('Do you have permission from your parents?', ['Yes']); 
    let posResult1 = 'yes';
    let posResult2 = 'Yes';
    let posResult3 = 'YES';


    let negResult1 = 'no';
    let negResult2 = 'No';
    let negResult3 = 'NO';

    if (confirmation) {
        if (posResult1 || posResult2 || posResult3) {
            return 'Access Granted!';               
        }
        else if (negResult1 || negResult2 || negResult3) {
            return 'Access Denied!';
        }
    }
    else {
        return 'Wrong Input Sucker!';
    }

    return confirmation;
  }

 }

 alert( ageChecker(age) );

3 个答案:

答案 0 :(得分:0)

确认变量的输出不应与多个变量进行比较,而应仅使用toLowerCase()函数

let age = prompt('How old are you?', [18]);

function ageChecker(age) {
    

    if (age >= 18) {
       return 'Access Granted!';
    } 
    else if (!age) {
       return 'Sorry Enter Your Age!';    
    }
    else {
       
        let confirmation = prompt('Do you have permission from your parents?', ['Yes']);
        if ('yes' == confirmation.toLowerCase()) {
            return 'Access Granted!';
        }else if('no' == confirmation.toLowerCase()){
          return 'Access Denied!';
        }else if(!confirmation){
          return 'Try next time';
        }
        else {
            return 'Wrong Input Sucker!';
        }
        
    return confirmation;
    }

   }

   alert( ageChecker(age) );

答案 1 :(得分:0)

几件事要注意:

  • 从提示符处得到的结果为 string 类型,因此,如果您使用age >= 18,将无法进行正确的比较。因此,如果希望用户输入数字,则应使用parseInt()转换结果。

  • 提示的答案存储在为提示功能分配的变量中,因此,如果执行const foo = prompt("What is your name");,答案将存储在变量foo中。因此,您的if语句需要检查confirmation变量。

  • 如果您不重新分配变量,请养成使用常量的习惯(即const foo = ...而不是let foo = ...)。

  • 最后,您可以使用toLowerCase(),因此只需将确认答案与“是”和/或“否”进行比较。

这是您可以代替编写函数的一种方式:

const age = parseInt( prompt('How old are you?', [18]), 10 );

function ageChecker(age) {
  if (!age) {
    return 'Sorry Enter Your Age!';   
  }

  if (age >= 18) {
      return 'Access Granted!';
  } 
  else {
    const confirmation = prompt('Do you have permission from your parents?', ['Yes']);
    
    if (!confirmation) {
      return 'Wrong Input Sucker!';
    }
    
    if (confirmation.toLowerCase() === 'yes') {
      return 'Access Granted!';
    }
    else if (confirmation.toLowerCase() === 'no') {
      return 'Access Denied!';
    }
    
    return 'Wrong Input Sucker!';
  }
 }

alert( ageChecker(age) );

检查confirmation时可以做的另一件整洁的事情是使用switch语句而不是if语句:

const age = parseInt( prompt('How old are you?', [18]), 10 );

function ageChecker(age) {
  if (!age) {
    return 'Sorry Enter Your Age!';   
  }

  if (age >= 18) {
      return 'Access Granted!';
  } 
  else {
    const confirmation = prompt('Do you have permission from your parents?', ['Yes']);
    
    if (!confirmation) {
      return 'Wrong Input Sucker!';
    }

    switch (confirmation.toLowerCase()) {
      case 'yes':
        return 'Access Granted!';
        
      case 'no':
        return 'Access Denied!';
        
      default:
        return 'Wrong Input Sucker!';
    }
  }
 }

alert( ageChecker(age) );

根据用途,与使用一堆if语句相比,switch语句可以是一种更整洁的变量检查方法。

答案 2 :(得分:0)

我将用 Yannik 的答案进行扩展,并提供一些我认为是JavaScript代码最佳实践的建议。

  1. 使用变量描述if语句中的条件。对于其他开发人员而言,它更易于阅读,尤其是在存在多个条件的情况下,例如hasValidAgelocatedInEuropeisAdmin

  2. 如果该方法返回了某些内容,请在方法末尾将其返回。这不仅使代码更清楚其功能,而且还使您有机会通过变量名解释返回的内容。

  3. 重构代码。现在,您的ageChecker带有长的if语句,这使得它很难阅读。不仅如此,您还拥有一种可以使两个产生作用的方法。它不仅检查年龄,还要求父母的许可。最好的情况下,一种方法只能做一件事情。

我标记了以下代码以突出我的观点。

[EDIT]根据评论中的问题进行的澄清:

a)如果用户删除了所有文本,则提示可能返回undefined。这将使代码稍后通过confirmation.toLowerCase()崩溃。

const confirmation = prompt('Do you have permission from your parents?', ['Yes']) // can return undefined

b)在我的重构示例中,我不想过多地偏离您的代码。如果我正确完成了重构,那么我将使用三种方法:

function ageCheckerAlert() {
  let messageStr = promptAge();
  const invalidAge = messageStr == 'Invalid Age'; 

  if (invalidAge) {
    messageStr = promptParentsPermission();
  }

  alert(messageStr);
}

function promptAge() {
  let messageStr = 'Invalid Age';
  const age = parseInt( prompt('How old are you?', [18]), 10 );

  // if statements that changes messageStr, if either valid age or empty input.

  return messageStr;
}

function promptParentsPermission() {
  // same code as in parentsPermissionChecker() in the snippet below
}

通过分离功能,您将获得额外的好处,即如果需要,可以单独调用promptAge()promptParentsPermission()

const age = parseInt( prompt('How old are you?', [18]), 10 );

function ageChecker(age) {
  let messageStr;
  const hasValidAge = age >= 18;  // 1

  if (!age) {
    messageStr = 'Sorry Enter Your Age!';   
  }
  else if (hasValidAge) {  // 1
    messageStr = 'Access Granted!';
  } 
  else {
    messageStr = parentsPermissionChecker(); // 3
  }

  return messageStr;  // 2
}

function parentsPermissionChecker() {  // 3
  const confirmation = prompt('Do you have permission from your parents?', ['Yes']) || ''; // added a default string.
  let messageStr = 'Wrong Input Sucker!';
  const typedYes = confirmation.toLowerCase() === 'yes';
  const typedNo = confirmation.toLowerCase() === 'no';

  if (typedYes) {
    messageStr = 'Access Granted!';
  }
  else if (typedNo) {
    messageStr = 'Access Denied!';
  }

  return messageStr;  // 2
}

alert( ageChecker(age) );