Javascript evaluation order for operators

前端 未结 4 943
灰色年华
灰色年华 2020-12-16 21:02

Which of the following expressions will always precede left to right in all browsers(particularly IE6+, F3+, Opera 9+, Chrome)? For example the window should always alert

4条回答
  •  暖寄归人
    2020-12-16 21:52

    Operator precedence and order of evaluation are two entirely different things. In the expression "sqrt(9) + sqrt(16) * sqrt(25)" it is misleading to say that "the multiplication is done first.". It is correct to say "multiplication takes precedence over addition.".

    The operations are:

    1. sqrt(9)
    2. sqrt(16)
    3. sqrt(25)
    4. 4 * 5
    5. 3 + 20

    The first three could be done in any order, or -- gasp -- simultaneously if you have a four-core CPU and a browser that can take advantage of it. 1 must be done before 5, 2 and 3 must be done before 4, and 4 must be done before 5. There are no other guarantees.

    In the expression "a && (b / a)", JavaScript guarantees that a is evaluated first and b / a is not evaluated if a is zero. Many other languages including Fortran do not guarantee this, and can get a division-by-zero exception.

提交回复
热议问题