Javascript evaluation order for operators

前端 未结 4 930
灰色年华
灰色年华 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:49

    Evaluating the expression into a value (e.g. involving a function call) is always done left to right.

    However, once you are comparing two values, they are not converted into primitives in order to do the actual comparison in a left to right fashion. Try the following in Chrome, for example:

    var l = {valueOf: function() { alert("L"); }};
    var r = {valueOf: function() { alert("R"); }};
    
    l < r; //alerts "L", then "R"
    l > r; //alerts "R", then "L"
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-16 22:01

    I'm not sure what your use-case is, but this might be an option:

    function add() {
      var retval = 0;
      for (var i = 0; i < arguments.length; i++) {
        retval += arguments[i];
      }
      return retval;
    }
    
    function echoNum(num) {
      alert("Num: " + num);
      return num;
    }
    
    alert("Result: " + add(echoNum(1), echoNum(2)));
    
    0 讨论(0)
  • 2020-12-16 22:06

    ECMAScript 5 specifies the order of evaluation of the operands for all operators. In the case of every operator in your code snip the evaluation order is left-to-right. I'm not sure anyone could answer about the behavior of all browsers though.

    Edit: See also ECMAScript 3. Evaluation order is defined the same way.

    0 讨论(0)
提交回复
热议问题