检查一个布尔选项集 [英] Check exactly one boolean option set
本文介绍了检查一个布尔选项集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗯,这有点像hacky:
Well, this is kind of hacky:
function b2n(boo) {
return boo ? 1 : 0;
}
if(b2n(opt1) + b2n(opt2) + b2n(opt3) !== 1) {
throw new Error("Exactly one option must be set");
}
在Javascript中有更好的方法吗?使用任何
Is there a better way to do this in Javascript? Using any of
- 更智能的布尔/数字处理
- 偷偷摸摸的数组或功能操作
等等。欢迎使用Javascript和Node解决方案。
And so forth. Javascript and Node solutions welcome.
在我的实际问题中,选项来自Node模块指令器,因此我没有处理真正的布尔值,只是真实和虚假的东西。也可能有一个指挥官解决方案。
In my actual problem, the options are coming from the Node module commander, so I'm not dealing with true boolean, just truthy and falsy things. There may be a commander-solution too.
推荐答案
假设你有一系列选项,你可以这样做:
Assuming you had an array of options, you could do:
if(opts.filter(Boolean).length !== 1) {}
在我看来,你应该有一个变量有三个可能的状态而不是......
It seems to me though that you ought to have one variable with three possible states instead...
var opt = 'a'; // (or 'b', or 'c')
这篇关于检查一个布尔选项集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文