在简单函数或条件中组合4个布尔值

时间:2018-03-12 17:54:17

标签: javascript if-statement conditional-statements

我有4个布尔值。

next_is_left
next_is_right
next_is_above
next_is_below

首先,我想检查一下全部 true。然后我想检查一个false。如果两个false,则所有false

我想知道如何在一个简单的if条件/函数中解决这个问题。感谢。

4 个答案:

答案 0 :(得分:3)

 switch(next_is_left + next_is_right + next_is_above + next_is_below){
   case 0:
     console.log("all false");
     break;
   case 1:
     console.log("one true");
     break;
   case 2:
     console.log("two true");
     break;
   case 3:
     console.log("one false");
     break;
   case 0:
     console.log("all true");
     break;

 }

只需添加布尔值。

答案 1 :(得分:0)

如何计算真值的数量并使用switch case来处理结果呢?



let next_is_left = false;
let next_is_right = true;
let next_is_above = true;
let next_is_below = false;

switch (getNumTrue(next_is_left, next_is_right, next_is_above, next_is_below)) {
    case 0:
        console.log(`All false`);
        break;
    case 1:
        console.log(`1 true, 3 false`);
        break;
    case 2:
        console.log(`2 true, 2 false`);
        break;
    case 3:
        console.log(`3 true, 1 false`);
        break;
    case 4:
        console.log(`All true`);
        break;
}    

function getNumTrue() {
    let i, numTrue;
    numTrue = 0;
    for (i = arguments.length - 1; i > -1; i--) {
        numTrue += arguments[i] ? 1 : 0;
    }
    return numTrue;
}




答案 2 :(得分:0)

您可以使用every方法来检查所有这些方法是真还是假,并过滤以查看有多少

var next_is_left = true;
var next_is_right = true;
var next_is_above = true;
var next_is_below = true;

var sides = [
  next_is_left,
  next_is_right,
  next_is_above,
  next_is_below,
];

sides.every(n => n === true); // checks if all true
sides.every(n => n === false); // checks if all false
sides.filter(n => n === false).length; // returns number of false variables

答案 3 :(得分:0)

使用数组来完成工作。

var booleans = [
  next_is_left
  next_is_right
  next_is_above
  next_is_below
];

var holdsTrue = function(arg) { return arg; };
var holdsFalse = function(arg) { return !arg; };


var theyAreAllTrue = booleans.filter(holdsTrue).length === booleans.length;
var oneOfThemIsFalse = booleans.filter(holdsFalse).length > 0;
var twoOfThemIsFalse = booleans.filter(holdsFalse).length > 1;
var threeOfThemIsFalse = booleans.filter(holdsFalse).length > 2;
var theyAreAllFalse = booleans.filter(holdsFalse).length === booleans.length;

还有lodash你有每一个,一些,否定,身份和大小

var theyAreAllTrue = every(booleans, identity)
var theyAreAllFalse = every(booleans, negate(identity));
var numberOfFalseOnes = size(filter(booleans, negate(identity)))
var numberOfTrueOnes = size(filter(booleans, identity))

var oneOfThemIsTrue = some(booleans, identity)
var oneOfThemIsFalse = some(booleans, negate(identity))