Javascript有没有一种方法可以简化对一个值的多次检查?
我有以下代码:Javascript有没有一种方法可以简化对一个值的多次检查?,javascript,Javascript,我有以下代码: if (tes.test.userTestStatusId != UserTestStatus.MarkedByAdmin && tes.test.userTestStatusId != UserTestStatus.MarkedByUser && tes.test.userTestStatusId != UserTestStatus.Paused && tes.test.userTestStatusId !
if (tes.test.userTestStatusId != UserTestStatus.MarkedByAdmin &&
tes.test.userTestStatusId != UserTestStatus.MarkedByUser &&
tes.test.userTestStatusId != UserTestStatus.Paused &&
tes.test.userTestStatusId != UserTestStatus.Completed) {
是否有某种方法可以简化此过程,以避免每次重复“tes.test.userTestStatusId”?您可以缓存该值
var userId = tes.test.userTestStatusId;
if (userId != UserTestStatus.MarkedByAdmin &&
userId != UserTestStatus.MarkedByUser &&
userId != UserTestStatus.Paused &&
userId != UserTestStatus.Completed)
{
将状态放入数组中
var statuses = [ UserTestStatus.MarkedByAdmin, UserTestStatus.MarkedByUser, UserTestStatus.Paused, UserTestStatus.Completed];
现在检查索引
if ( statuses.indexOf( userId ) == -1 )
您可以缓存该值
var userId = tes.test.userTestStatusId;
if (userId != UserTestStatus.MarkedByAdmin &&
userId != UserTestStatus.MarkedByUser &&
userId != UserTestStatus.Paused &&
userId != UserTestStatus.Completed)
{
将状态放入数组中
var statuses = [ UserTestStatus.MarkedByAdmin, UserTestStatus.MarkedByUser, UserTestStatus.Paused, UserTestStatus.Completed];
现在检查索引
if ( statuses.indexOf( userId ) == -1 )
如果“严格相等”正常,则可以将值存储为数组并使用:
如果“严格相等”正常,则可以将值存储为数组并使用:
这将不会少很多代码,但会更加稳定-您可以在不必更改代码的情况下从status对象中添加/删除案例 其思想是遍历
UserTestStatus
属性,并查找任何匹配项:
if (!Object.keys(UserTestStatus).some(function(key) {
return UserTestStatus[key] == test.test.userTestStatusId;
})) {
// no matches found
}
现在,如果您返回并添加一个新案例(可能是
UserTestStatus.Failed
或UserTestStatus.NotStarted
),则代码不必更改。这不会减少多少代码,但会更加稳定-您可以在不更改代码的情况下从status对象中添加/删除案例
其思想是遍历UserTestStatus
属性,并查找任何匹配项:
if (!Object.keys(UserTestStatus).some(function(key) {
return UserTestStatus[key] == test.test.userTestStatusId;
})) {
// no matches found
}
现在,如果您返回并添加一个新案例(可能是UserTestStatus.Failed
或UserTestStatus.NotStarted
),则代码不必更改。您可以使用:
但我个人认为普通的有条件方法更干净。您可以使用:
但我个人认为普通的条件方法更干净。如果我正确理解了您的问题,您可以将id保存在新的var中,然后在If条件下使用它,如下所示:
var statusId=tes.test.userTestStatusId;
if ( statusId!= UserTestStatus.MarkedByAdmin &&
statusId != UserTestStatus.MarkedByUser &&
statusId != UserTestStatus.Paused &&
statusId != UserTestStatus.Completed) {
但是,如果您正在寻找在一次使用中组合多个逻辑检查的方法,据我所知,它将不会有效如果我正确理解您的问题,您可以将id保存在新的var中,然后在如下if条件下使用它:
var statusId=tes.test.userTestStatusId;
if ( statusId!= UserTestStatus.MarkedByAdmin &&
statusId != UserTestStatus.MarkedByUser &&
statusId != UserTestStatus.Paused &&
statusId != UserTestStatus.Completed) {
但是,如果您正在寻找将多个逻辑检查组合在一个使用中的方法,据我所知,它将不会有效