简体   繁体   English

如何将两个语句转换成三元

[英]how can I turn two statements into a ternary

I have two if statements that'd like to turn into a ternary but I don't know how. 我有两个if语句想要变成三元组,但是我不知道如何。

if (val === true && optval === 'car' || val === true && optval === 'truck' )view_list.style.display = 'none';
if (val === true && optval === 'buss' || val === true && optval === 'van')view_list.style.display = '';

Apart in hacks I won't mention, a ternary is used when you want to return a value in all cases. 除了我不会提到的hack,在所有情况下您都想返回值时使用三元数。

If val isn't true , then you do nothing. 如果val不是true ,那么您什么也不做。

Therefore this can't be used here. 因此,不能在这里使用它。

view_list.style.display = 
  (val === true && optval === 'car' || 
   val === true && optval === 'truck' ) ? 
     'none' : 
     ((val === true && optval === 'buss' || 
       val === true && optval === 'van') ? 
         '' : 
         view_list.style.display ) ;

or more succinctly : 或更简洁:

view_list.style.display = 
  (val === true && ( optval === 'car' || optval === 'truck' ) ) ?
     'none' : 
     ((val === true && ( optval === 'buss' || optval === 'van' ) ? 
         '' : 
         view_list.style.display  );

The parentheses around the second conditional are optional. 第二个条件的括号是可选的。

Of course this is not really a good approach, and this answer should not be seen as an endorsement to this style of programming. 当然,这并不是真正的好方法,不应将此答案视为对这种编程风格的认可。

Not what you were asking for, but as @dystroy said, this is not the best case for a ternary. 不是您的要求,而是正如@dystroy所说的,对于三元组来说,这不是最好的情况。

But you can still make it a bit more elegant. 但是您仍然可以使其更加优雅。 How about 怎么样

var styleMapping = {
    'car': 'none',
    'truck': 'none',
    'buss': '',
    'van': ''
};

// Apparently val is always required in your example
if (val) {
    view_list.style.display = styleMapping[optval];
}

This also has the benefit that refactoring and adding new styles is very easy without having to write much code. 这还有一个好处,那就是重构和添加新样式非常容易,而无需编写太多代码。 Just add one line in the mapping and you're done. 只需在映射中添加一行就可以了。 And of course it's much more readable and closer to what you intend to do. 当然,它更易读,更接近您的意图。

You don't really care about boolean logic, you just want to have a different style based on what optval is set to. 您实际上并不关心布尔逻辑,只是想根据optval设置的样式而有所不同。

Because nobody has said it yet, switch 由于尚未有人说过,请switch

if (val === true)
    switch (optval) {
        case 'car':
        case 'truck':
            view_list.style.display = 'none';
            break;
        case 'buss':
        case 'van':
            view_list.style.display = '';
            break;
    }

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

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