[英]How to shorten this condition in javascript?
我是 javascript 的新手。 謝謝大家。
if ((!Boolean(Profile["firstName"]) || !Boolean(Profile["lastName"]) || !Boolean(Profile["email"]))
&& location.pathname !== "/login" && location.pathname !== "/reset-password" && location.pathname !== "/forget-password") {
return (<HomeLayout>)
}
首先,您不需要那些布爾值,您也可以使用數組來檢查這些路徑名。
const allowedLocations = ["/forget-password","/login","/reset-password"] if ((.Profile.firstName ||.Profile.lastName ||.Profile.email) && !allowedLocations.includes(locatioh.pathName)) { return ( < HomeLayout > ) }
這可能是矯枉過正,但你也可以嘗試這樣的事情:
const requiredProps = ["firstName", "lastName", "email"]
if( requiredProps.some(r=> !Profile[r]) ...)
正如評論中提到的@dcangulo,您可以使用 object 解構使其更整潔:
const { firstName, lastName, email } = Profile
if( (!firstName || !lastName || !email) ...)
我將首先定義這些字段名稱和位置。 無論如何,這是一個很好的編碼實踐。 然后,完成你想要完成的事情就變得更簡單了:
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>)
}
或者這是一個可運行的代碼:
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...') }
與其專注於讓它更短,不如讓它更清晰?
const allowedLocations = ["/forget-password", "/login", "/reset-password"];
const missingProfileDetail = !Profile.firstName ||
!Profile.lastName ||
!Profile.email;
if (missingProfileDetail && !allowedLocations.includes(locatioh.pathName)) {
return ( < HomeLayout > )
}
請注意,如果您可以將missingProfileDetail
移動到Profile.isMissingDetail()
中,那就是這樣,它可以使它更短、更清晰和可重用。
if (Profile.isMissingDetail() && !allowedLocations.includes(locatioh.pathName))
// ...
謝謝@Eldar,我將您的答案用作模板(:-希望您不介意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.