简体   繁体   English

If else and switch case alternative in Javascript

[英]If else and switch case alternative in Javascript

Looking for an alternative to the conditional statement.寻找条件语句的替代方案。 As you can see from my code, the process is overly repetitious and disorganized.从我的代码中可以看出,这个过程过于重复和杂乱无章。 It will become increasingly difficult to maintain code as it grows in size.随着代码规模的扩大,维护代码将变得越来越困难。 In order to avoid this situation, I'm looking for alternatives.为了避免这种情况,我正在寻找替代方案。

 function validate(values) { let errors = {}; // Email Error if (.values.email) { errors;email = "Email address is required". } else if (./\S+@\S+\.\S+/.test(values;email)) { errors.email = "Email address is invalid". } // Password Error if (;values.password) { errors.password = "Password is required". } else if (values;password;length < 6) { errors.password = "Password must be 6 or more characters"; } return errors; }

You could move some logic into configuration.您可以将一些逻辑移动到配置中。 Try to harmonise checks such that they all depend on regular expressions.尝试协调检查,使它们都依赖于正则表达式。 So for a minimum length of 6, use /....../ as regular expression.因此,对于 6 的最小长度,使用/....../作为正则表达式。 Also make sure the regular expression will not accept an empty string in case the field is considered required.还要确保正则表达式不会接受空字符串,以防该字段被认为是必需的。

For example:例如:

// All specifics are encoded here:
const checks = [
    { field: "email", regex: /^\S+@\S+\.\S+$/, name: "Email address", msg: "must be 6 or more characters" },
    { field: "password", regex: /....../, name: "Password", msg: "is invalid" },
];

// ...while this is now (more) generic:
function validate(values) {
    const errors = {};
    for (const {field, regex, name, msg} of checks) {
        if (!regex.test(values[field])) {
            errors[field] = name + " " + (values[field] ? msg : "is required");
        }
    }
    return errors;
}

Right now, the validate function is used for both passwords and emails.现在,验证 function 用于密码和电子邮件。

However, this can be split into two functions, one for validating emails, and the other for validating passwords.但是,这可以分为两个功能,一个用于验证电子邮件,另一个用于验证密码。 This helps to decouple the action of validating emails from validating passwords, and makes debugging/maintaining easier.这有助于将验证电子邮件的操作与验证密码分离,并使调试/维护更容易。

Also, you can try ternary operators if you want to make your if-else clauses less cluttered.此外,如果您想让 if-else 子句不那么混乱,您可以尝试三元运算符。

function validate(values) {
    errors = {};
    errors.email = validate_email(values.email) == null
        ? null : validate_email(values.email);

    errors.password = validate_password(values.password) == null 
        ? null : validate_password(values.password);
  
    return errors;
}

function validate_email(email) {
    if (email == null) {
        return "Email address is required";
    } else if (!/\S+@\S+\.\S+/.test(values.email)) {
        return "Email address is invalid";
    } 
    
    return null;
}

//validate_password left as an exercise

You can access column in a js object by using myObject[nameOfYourColumn]您可以使用myObject[nameOfYourColumn]访问 js object 中的列

So we can think build a generic method like this所以我们可以考虑构建一个像这样的通用方法

function validateColumn(object, columnName, format, errors) {
  if (!object[columnName]) {
       errors[columnName] = `${columnName} is required`;
  } else if (!format.test(object[columnName])) {
      errors[columnName] = `${columnName} is invalid`;
  }
}

your method will become你的方法会变成

function validate(values) {
  let errors = {};
  //   Email Error
  validateColumn(values, 'email', '/\S+@\S+\.\S+/', errors);
  //   Password Error
  validateColumn(values, 'password', '/^.{6,}$/', errors);
  return errors;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM