javascript - if 语句基于 3 个不同的条件
问题描述
假设我有一个用户角色列表,并且有 3 个条件将用户重定向到一个页面,并且它基于设置值。
我在下面有我的代码,这是最干净的方法吗?我正在寻求建议。谢谢。
条件是
settings - if settings has value and user roles not equal to broker -> navigate to properties page
settings - if settings has no value and user role is equal to broker -> navigate to navigate to transaction page
settings - if settings has no value and user role not equal to broker -> navigate to index page
#user 角色 ["admin, "broker", "manager" , "consultant"]
#代码
this.userService.updateUserProfileSettings(oldUserProfile)
.subscribe(
res =>{
const forwardToPage = localStorage.getItem('forwardToPage');
if(settings && role !== 'Broker'){
this.route.navigateByUrl('/properties');
}else if (!settings && role === 'Broker') {
this.route.navigateByUrl('/transactions');
}else{
this.route.navigateByUrl('/index');
}
},
解决方案
你可以这样做
(但你忘记了 的情况settings has value and user role is equal to broker
)
const target = ['/index','/properties','/transactions','??index' ]
function test ( settings,role )
{
let condition = (settings ? 1 : 0) + (role === 'Broker' ? 2 : 0)
console.log (`settings is ${settings} and role is ${role} ==> ${target[condition]}` )
}
test( true, 'not Broker' )
test( false, 'Broker' )
test( false, 'not Broker' )
test( true, 'Broker' )
.as-console-wrapper { max-height: 100% !important; top: 0 }
推荐阅读
- ruby-on-rails - 如何仅渲染数组中的两条路径?
- oracle - 如何在两列上设置相同的序列号
- java - 在 Spring Boot 中重新创建查询
- reactjs - 使用 GraphQL 自定义输入类型的正确方法是什么?
- c - Codelite 找不到流
- c - 无法使用 CMake 和 Visual Studio 2019 在 Windows 10 上编译,因为它找不到 MSBuild 或编译器
- python - 读取存储为字节的文本文件
- python - 如何仅从特定节点的邻接矩阵创建网络图?
- python - 如何在 Python 中编写两步计算器代码?
- javascript - 无法将修改后的字符串推送到 javascript 数组