How to make a boolean variable switch between true and false every time a method is invoked?

后端 未结 9 1005
南旧
南旧 2020-12-13 09:01

I am trying to write a method that when invoked, changes a boolean variable to true, and when invoked again, changes the same variable to false, etc.

For example: ca

相关标签:
9条回答
  • 2020-12-13 09:25

    Assuming your code above is the actual code, you have two problems:

    1) your if statements need to be '==', not '='. You want to do comparison, not assignment.

    2) The second if should be an 'else if'. Otherwise when it's false, you will set it to true, then the second if will be evaluated, and you'll set it back to false, as you describe

    if (a == false) {
      a = true;
    } else if (a == true) {
      a = false;
    }
    

    Another thing that would make it even simpler is the '!' operator:

    a = !a;
    

    will switch the value of a.

    0 讨论(0)
  • 2020-12-13 09:25

    I do it with boolean = !boolean;

    0 讨论(0)
  • 2020-12-13 09:25
    var logged_in = false;
    logged_in = !logged_in;
    

    A little example:

    var logged_in = false;
    
    
    $("#enable").click(function() {
        logged_in = !logged_in;
        checkLogin();
    });
    
    function checkLogin(){
        if (logged_in)
            $("#id_test").removeClass("test").addClass("test_hidde");
        else
            $("#id_test").removeClass("test_hidde").addClass("test");
        $("#id_test").text($("#id_test").text()+', '+logged_in);
    }
    .test{
        color: red;
        font-size: 16px;
        width: 100000px
    }
    
    .test_hidde{
        color: #000;
        font-size: 26px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="test" id="id_test">Some Content...</div>
    <div style="display: none" id="id_test">Some Other Content...</div>
    
    
    <div>
        <button id="enable">Edit</button>
    </div>

    0 讨论(0)
  • 2020-12-13 09:26

    Just toggle each time it is called

    this.boolValue = !this.boolValue;
    
    0 讨论(0)
  • 2020-12-13 09:26
    value = (value) ? false : true;
    

    Conditional (ternary) Operator.

    0 讨论(0)
  • 2020-12-13 09:28

    in java when you set a value to variable, it return new value. So

    private boolean getValue()
    {
         return value = !value;
    }
    
    0 讨论(0)
提交回复
热议问题