开发者

Javascript order of evaluation

Came across this JS snippet, and I honestly have NO id开发者_运维问答ea of what order things are being evaluated in... Any ideas? Parentheses would be helpful...

return point[0] >= -width / 2 - allowance &&
       point[0] <= width / 2 + allowance && 
       point[1] >= -height / 2 - allowance && 
       point[1] <= height / 2 + allowance;


https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence

The relavant operators go in this order: unary negation, division, addition/subtraction, relational (>=, <=), logical and.

return (point[0] >= ((-width / 2) - allowance))
    && (point[0] <= ((width / 2) + allowance))
    && (point[1] >= ((-height / 2) - allowance))
    && (point[1] <= ((height / 2) + allowance))


Equivalent to:

return
    (point[0] >= ((-width  / 2) - allowance))
 && (point[0] <= (( width  / 2) + allowance))
 && (point[1] >= ((-height / 2) - allowance))
 && (point[1] <= (( height / 2) + allowance));


check this

function bob(n){
  alert(n);
  return n;
}

return bob(1) >= bob(2) / bob(3) - bob(4) &&
       bob(5) <= bob(6) / bob97) + bob(8) && 
       bob(9) >= bob(10) / bob(11) - bob(12) && 
       bob(13) <= bob(14) / bob(15) + bob(16);


Adding paratheses and some indentation should make it clearer:

return 
  point[0] >= (-width / 2) - allowance 
    && 
  point[0] <= (width / 2) + allowance 
    && 
  point[1] >= (-height / 2) - allowance 
    && 
  point[1] <= (height / 2) + allowance;


return (point[0]) >= (-width / 2 - allowance) && (point[0] <= width / 2 + allowance) && (point[1] >= -height / 2 - allowance) && (point[1]) <= (height / 2 + allowance);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜