我需要设计一个具有 2 个条件 a 和 b 的全局布尔值,这样如果 A 为真,则布尔值为真,直到 b 为真,此时布尔值为假。换句话说,如果 A 变为假,则布尔值仍然为真。
我尝试了一个简单的全局变量,但是当 A 变为 false 时它变为 false。
最好是 JavaScript,但伪代码几乎同样有用。
我需要设计一个具有 2 个条件 a 和 b 的全局布尔值,这样如果 A 为真,则布尔值为真,直到 b 为真,此时布尔值为假。换句话说,如果 A 变为假,则布尔值仍然为真。
我尝试了一个简单的全局变量,但是当 A 变为 false 时它变为 false。
最好是 JavaScript,但伪代码几乎同样有用。
如果我正确理解您的问题,那么将这些案例与
var bool = (a != b);
/*
    (false != false) = false
    (true != false) = true
    (false != true) = true
    (true != true) = false
*/
通过您的更改,您可以创建一个全局变量var aWasEverTrue = a;,而不是a直接设置,而是使用诸如setA(true).
var a = false;
var b = false;
var aWasEverTrue = a;
function setA(newAValue) {
    aWasEverTrue = true;
    a = newAValue;
}
// (aWasEverTrue != b) = false
setA(true);
// (aWasEverTrue != b) = true
b = true;
// (aWasEverTrue != b) = false
setA(false);
// (aWasEverTrue != b) = false (as aWasEverTrue is still true)
b = false
// (aWasEverTrue != b) = true
    这听起来像一个异或。IE
!A and !B == false
A and !B == true
!A and B == true
A and B == false
不幸的是,JavaScript 没有逻辑 XOR 运算符,但是
如果(A?!B:B){
在功能上是等效的
Javascript老派方式:
function Enjoy() {
    this.a = true;
    this.b = true;
    this.bool = true;
}
Enjoy.prototype = {
    constructor: Enjoy,
    setA: function( val ) {
        this.a = val;
        if ( this.a === true && this.b === true ) this.bool = false;
        else if ( this.a === true && this.b === false ) this.bool = true;
    },
    setB: function( val ) {
        this.b = val;
        if ( this.a === true && this.b === true ) this.bool = true;
        else if ( this.a === true && this.b === false ) this.bool = false;
    },
    getBool: function() {
        return this.bool;
    }
};
var enjoy = new Enjoy();
enjoy.getBool(); // true
enjoy.setB( false );
enjoy.getBool(); // false
如您所见,我们的想法是为您的布尔值a和b变量使用 getter/setter,您可以在其中执行所有逻辑。
顺便说一句,这个问题绝对是针对 StackOverflow 的。
你想要的是一个状态机
结果状态:
T (True)
F (False)
过渡:
F -- a (true) --> T
F -- anything else --> F
T -- b (true) --> F
T -- anything else --> T
可以用一系列ifs来表达
基于如果 A 不为真,B 应该如何表现的一些假设:
function FlipFlop(){
    this.latch = false;
    this.value = false;
}
FlipFlop.prototype = {
    constructor: FlipFlop,
    setA: function( val ) {
        this.latch = this.latch || !!val;
        this.value = this.latch;
    },
    setB: function( val ) {
        if(this.latch && !!val) {
            this.latch = false;
        }
        this.value = !val;
    },
    getVal: function() {
        return this.value;
    }
}