search

Home  >  Q&A  >  body text

In the logical operation of JavaScript, a small question about --c and c--.

Teacher Han said:

<script type=text/javascript>

var a = 3;

var b = 4;

var c = 1;

if ( a < b && --c && a)

{

window.alert("OK")

}

window.alert(c) // c = 0

window.alert(a) // a =3

If you change "--c "becomes "c--"". At this time, the value of c is also 0. Why does the value of a change to 4?

I hope all teachers can answer it, thank you!

正歌正歌2497 days ago1760

reply all(5)I'll reply

  • 一切近乎完美

    一切近乎完美2018-03-28 15:24:52

    --c is calculated first and then assigned to c, that is, kill first and report later. When you kill him, the emperor doesn't know yet and thinks he is not dead yet, so c is still the original c. He will only know it after reporting it. , he is dead, and c is reduced by one.

    And c-- was subtracted and assigned to c. At that time, c was one less, which meant that the emperor personally supervised the execution.


    reply
    1
  •  

     2018-03-27 10:57:45

    For --c

    a < b true

    --c c decrements first c=0 false (0 is false, non-0 is true)

    a<b&&--c false then the "short circuit" of && will be triggered and will not be executed++a

    all c=0, a=3

    for c--

    a < b true

    c-- c first determines whether it is true or false and then decrements itself. In all judgments, c=1 is true, and then c decrements itself

    a<b&&--c true will not Trigger the "short circuit" of && and execute and judge ++a

    so c=0, a=4

    reply
    1
  • 正歌

    Thank you, I figured it out.

    正歌 · 2018-03-27 11:08:21
  • 一生何求

    一生何求2018-03-26 21:13:25

    --c, the left side of the expression is false, and ++a on the right side is not operated, so the value of a is still 3

    When c++, the left side of the expression is true, so ++a on the right side is still needed Perform operations, so the value of a becomes 4

    reply
    2
  • 正歌

    正歌2018-03-26 19:48:14

    <script type=text/javascript>

    var a = 3;

    var b = 4;

    var c = 1;

    if (a < b && c-- && ++a); //At this time, the value of c is also 0, which should also be false. ++a should not perform the operation, so the value of a should still be 3 That's right, why are you calculating it?

    {

    window.alert("OK")

    }

    window.alert(c) // c = 0

    window.alert(a) // a =3


    reply
    0
  • Cancelreply