edit1:为javascript修改,而不是java。哎呀...
我不确定您是否想查看所有组合,但您可以通过为每个可能的输出引入一个数值来对它们进行分组。
具体有5个变量和每个变量2个选项?我已经用二进制表示的数字设置了一个表。如果每个(或某些)变量有 > 2 个选项,则必须使用数字(以 10 为底)。您可以使用二进制值,例如
const locVal = (loc > 0 ? 0x1 : 0x0) << 0;
const catVal = (cat < 0 ? 0x1 : 0x0) << 1;
const priceVal= (price < 0 ? 0x1 : 0x0) << 2;
ect
因此,您可以将它们分组到一个方法中:
function foo(trueCond, level) {
return (trueCond ? 0b1 : 0b0) << level;
}
这使得
const locVal = foo(loc > 0, 0);
const catVal = foo(cat > 0, 1);
const priceVal= foo(price > 0, 2)
(我省略了其他变量...)然后将二进制值相加
const total = locVal + catVal + priceVal
然后你现在必须使用 switch case 语句,如
switch (total) {
case 0: // all options negative
case 1: // only loc is positive
case 2: // only cat is positive
case 3: // both loc and cat is positive
ect
}
中的值case
表示存在于 中的二进制序列的整数值total
。必须注意的是,将代码记录得非常好,尤其是案例块非常重要,这样其他读者就可以直接找出哪个值代表什么(就像我所做的那样)。
如果每个变量有两个以上的选项,您可以以 10 的因子工作(如在方法 foo 中,使用(trueCond ? 1 : 0) * Math.pow(10, level)
)