如何确保对象中的一个属性在javascript中始终为真

hgncfbus  于 2021-09-29  发布在  Java
关注(0)|答案(2)|浏览(320)

我有一个过滤器对象,如图所示。默认情况下,一次只能有一个筛选器为true unread 这是真的。
如果 read 如果设置为true,则其他两个为false。
如果 read 默认情况下设置为false unread 应该设置为真。
如何通过调用函数来实现这一点 updateFilter(filter,value) 或者建议一个更好的方法。

var filter = {
unread: true,
read: false,
all: false
}

html部分:

<div class="gb-notification-action-top-switch">
   <div class="gb-notification-action-top-switch-text"> Unread:</div>
   <span class="gb-switch filter-btn"ng-click="healthCtrl.info.noti_filter.unread = !healthCtrl.info.noti_filter.unread;healthCtrl.notificationFilterChange('unread')" ng-class="{'active':  healthCtrl.info.noti_filter.unread }">
      <div class="gb-switch-handle"></div>
   </span>
</div>
<div class="gb-notification-action-top-switch">
   <div class="gb-notification-action-top-switch-text"> Read:</div>
   <span class="gb-switch filter-btn"ng-click="healthCtrl.info.noti_filter.read = healthCtrl.info.noti_filter.read;healthCtrl.notificationFilterChange('read')" ng-class="{'active':  healthCtrl.info.noti_filter.read }">
      <div class="gb-switch-handle"></div>
   </span>
</div>
<div class="gb-notification-action-top-switch">
   <div class="gb-notification-action-top-switch-text"> All:</div>
   <span class="gb-switch filter-btn"ng-click="healthCtrl.info.noti_filter.all = !healthCtrl.info.noti_filter.all;healthCtrl.notificationFilterChange('all')" ng-class="{'active':  healthCtrl.info.noti_filter.all }">
      <div class="gb-switch-handle"></div>
   </span>
</div>

vdzxcuhz

vdzxcuhz1#

您可以尝试这样做:

const filter = {
    unread: false,
    read: true,
    all: false
}

const updateFilter = (keyName, value) => {
  for (let key in filter) {
    filter[key] = (key === keyName) ? value : false;
  }
  if (!Math.max.apply(null, Object.values(filter))) filter.unread = true;
}

updateFilter('read', false);
console.log(filter);
qltillow

qltillow2#

此函数应实现以下功能:

function updateFilter(filter, target_filter){
    for (var f of Object.keys(filter)){
        filter[f] = false
    }
    filter[target_filter] = true
}

函数只需迭代过滤器的所有属性并将其设置为false,然后将目标选项设置为true。
所以,如果你做了如下事情:

var filter = {
unread: true,
read: false,
all: false
}

updateFilter(filter, "unread")

您的过滤器看起来像:

var filter = {
unread: true,
read: false,
all: false
}

updateFilter(filter, "all") 你会得到:

var filter = {
unread: false,
read: false,
all: true
}

诸如此类,诸如此类——你明白了。

相关问题