简体   繁体   English

建议如何简化此if语句

[英]Suggestions how to simplify this if statement

I have a code which is validating if all form fields are populated with data, but my form inputs are displayed dynamically based on this.id_company condition. 我有一个验证所有表单字段是否都填充有数据的代码,但是我的表单输入是根据this.id_company条件动态显示的。 As you can see if this.is_company equals TRUE then validation should also check if user has inserted this.taxNumber and this.copmany 如您所见,如果this.is_company等于TRUE那么验证还应该检查用户是否插入了this.taxNumberthis.copmany

isComplete: function () {
    if (this.is_company) {
        return this.firstName && this.lastName && this.email && this.password && this.address && this.postNumber
            && this.city && this.id_country && this.iAggre && this.taxNumber && this.company
    }
    return this.firstName && this.lastName && this.email && this.password && this.address && this.postNumber
        && this.city && this.id_country && this.iAggre;
}

I'm searching the best way to simplify my Javascript code. 我正在寻找简化Javascript代码的最佳方法。 Can you guy please provide examples. 能否请您提供示例。 Thank you 谢谢

To easy, just use an or: 为简单起见,只需使用或:

return (
   this.firstName && 
   this.lastName && 
   this.email && 
   this.password && 
   this.address && 
   this.postNumber && 
   this.city && 
   this.id_country && 
   this.iAggre && 
   (!this._isCompany || this.taxNumber && this.company)
);

To be read as and is not a company or has a taxNumber and a company property . 被理解为公司,不是公司,或具有taxNumber和公司财产

A nicer, easy to read version would be: 一个更好的,易于阅读的版本是:

isComplete: function () {
    var baseCondition = this.firstName && this.lastName && this.email 
        && this.password && this.address && this.postNumber
        && this.city && this.id_country && this.iAggre

    var companyCondition = baseCondition && this.taxNumber && this.company;

    return this.is_company ? companyCondition : baseCondition;
}

You could group your fields in an array, and conditionally push the company and taxNumber fields: 您可以将字段分组为一个数组,并有条件地推送companytaxNumber字段:

var validate = function(isCompany) {
  var validateFields = [
    this.firstName,
    this.lastName,
    this.email,
    this.password,
    this.address,
    this.postNumber,
    this.city,
    this.id_country,
    this.iAggre
  ];

  if (isCompany) {
    validateFields.push(this.company, this.taxNumber);
  }

  return validateFields.find(f => !f) === undefined;
}

var isComplete = function() {
  return validate(this.is_company);
}

Best bet is to reduce each function down to its simplest form. 最好的选择是将每个功能简化为最简单的形式。 @jonas-w was going in the right direction by computing values. 通过计算值,@ jonas-w朝着正确的方向发展。 The method name documents what the outcome means, and makes the conditional easier to understand. 方法名称记录了结果的含义,并使条件更易于理解。

You can always make isCompanyComplete() and isPersonComplete() private methods if you don't want to expose them. 如果不想公开它们,则可以始终将isCompanyComplete()isPersonComplete()私有方法。

Spreading the logical operators ( && ) over separate lines makes the statement much more readable. 将逻辑运算符( && )散布在单独的行中可使该语句更具可读性。

Splitting the ternary statement across separate lines also makes it clear which parts apply to logically true or false. 将三元语句拆分成单独的行也可以清楚地看出哪些部分适用于逻辑上的真或假。

Avoid inverting logic in conditions ( !this.is_company ). 避免在条件( !this.is_company )中反转逻辑。

 class Form { isPersonComplete() { return !!( this.firstName && this.lastName && this.email && this.password && this.address && this.postNumber && this.city && this.id_country && this.iAgree ); } isCompanyComplete() { return !!( this.isPersonComplete() && !!this.taxNumber && !!this.company ); } isComplete() { return this.is_company ? this.isCompanyComplete() : this.isPersonComplete(); } } const form = new Form() console.log( 'Person: ' + form.isPersonComplete(), 'Company: ' + form.isCompanyComplete(), 'Completed: ' + form.isComplete() ); form.firstName = 'John'; form.lastName = 'Smith'; form.email = 'john@smith.co'; form.password = 'somesecret'; form.address = '123 main street, anywhere'; form.postNumber = '12345'; form.city = 'Metropolis'; form.id_country = 1; form.iAgree = true; console.log( 'Person: ' + form.isPersonComplete(), 'Company: ' + form.isCompanyComplete(), 'Completed: ' + form.isComplete() ); form.is_company = true; form.taxNumber = 12345; form.company = 'John Smith & Co'; console.log( 'Person: ' + form.isPersonComplete(), 'Company: ' + form.isCompanyComplete(), 'Completed: ' + form.isComplete() ); 

That this question is "primarily opinion-based", etc is already established, so what the hell, here's another suggestion: 这个问题是“主要基于意见的”,等等,这已经确定了,那么到底是什么,这是另一个建议:

 function form() { this.vld = { fields: ["firstName", "lastName", "email", "password", "address", "postNumber", "city", "id_country", "iAggre"], check: arr => !arr.some(el => !this[el]), isComplete: () => this.vld.check(this.vld.fields) && (!this.is_company || this.vld.check(["taxNumber", "company"])) } } var stuff = new form(); stuff.firstName = "Alice"; stuff.lastName = "Bob"; stuff.email = "alice@bob.com"; stuff.password = "12abc123"; stuff.address = "123 Main St"; stuff.postNumber = "12345"; stuff.city = "Springfield"; stuff.id_country = 1; console.log(false, stuff.vld.isComplete()); stuff.iAggre = true; console.log(true, stuff.vld.isComplete()); stuff.is_company = true; stuff.taxNumber = "123456789"; console.log(false, stuff.vld.isComplete()); stuff.company = "Moe's"; console.log(true, stuff.vld.isComplete()); 

This method can potentially be optimized by grabbing the names of the input fields from the form itself, which would avoid restating all fields explicitly. 可以通过从表单本身获取输入字段的名称来优化此方法,这将避免显式地重新声明所有字段。

Does this work for you? 这对您有用吗?

isComplete: function () { 
    let result = this.firstName && this.lastName && this.email && this.password && this.address && this.postNumber && this.city && this.id_country && this.iAggre;
    if (this.is_company) result += this.taxNumber && this.company;
    return result; 
}

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

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