简体   繁体   English

如何在 javascript 中缩短此条件?

[英]How to shorten this condition in javascript?

I'm new with javascript.我是 javascript 的新手。 Thank-you every body.谢谢大家。

if ((!Boolean(Profile["firstName"]) || !Boolean(Profile["lastName"]) || !Boolean(Profile["email"]))
      && location.pathname !== "/login" && location.pathname !== "/reset-password" && location.pathname !== "/forget-password") {    
            return  (<HomeLayout>)
 }

Firstly you don't need those booleans and also you can use an array to check those path names.首先,您不需要那些布尔值,您也可以使用数组来检查这些路径名。

 const allowedLocations = ["/forget-password","/login","/reset-password"] if ((.Profile.firstName ||.Profile.lastName ||.Profile.email) && !allowedLocations.includes(locatioh.pathName)) { return ( < HomeLayout > ) }

it might be overkill but you can also try something like this:这可能是矫枉过正,但你也可以尝试这样的事情:

const requiredProps = ["firstName", "lastName", "email"]

if( requiredProps.some(r=> !Profile[r])  ...)

As @dcangulo mentioned in the comments you can use object destructuring to make it neater:正如评论中提到的@dcangulo,您可以使用 object 解构使其更整洁:

const { firstName, lastName, email } = Profile 
if( (!firstName || !lastName || !email) ...)

I would define those field names and locations first.我将首先定义这些字段名称和位置。 It's a good coding practice anyway.无论如何,这是一个很好的编码实践。 Then it becomes simpler to accomplish what you're trying to accomplish:然后,完成你想要完成的事情就变得更简单了:

const field_names = ["firstName", "lastName", "email"];
const locations = ["/forget-password", "/login", "/reset-password"];

if(field_names.find(i => !Profile[i]) || !locations.includes(location.pathName)){
  return  (<HomeLayout>)
}

Or here is a runnable code:或者这是一个可运行的代码:

 const field_names = ["firstName", "lastName", "email"]; const locations = ["/forget-password", "/login", "/reset-password"]; const Profile = {firstName: 'John', lastName: 'Done', email: ''} const pathName = '/login' if(field_names.find(i =>.Profile[i]) ||.locations.includes(pathName)){ console.log('Executing...') }

Rather than focus on making it shorter, how about making it clearer?与其专注于让它更短,不如让它更清晰?

const allowedLocations = ["/forget-password", "/login", "/reset-password"];
const missingProfileDetail = !Profile.firstName ||
                             !Profile.lastName ||
                             !Profile.email;
if (missingProfileDetail && !allowedLocations.includes(locatioh.pathName)) {
  return ( < HomeLayout > )
}

Note that if you can move missingProfileDetail into Profile.isMissingDetail() , that's the way, and it makes it shorter, clearer and reusable .请注意,如果您可以将missingProfileDetail移动到Profile.isMissingDetail()中,那就是这样,它可以使它更短、更清晰和可重用

if (Profile.isMissingDetail() && !allowedLocations.includes(locatioh.pathName))
// ...

Thank you @Eldar, I used your answer as a template (: - hope you don't mind.谢谢@Eldar,我将您的答案用作模板(:-希望您不介意。

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

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