Math.PI的相关运算

Math自增和自减的运算似乎是经典的一道面试题。


var a = (++Math.PI);   
alert(a); //1  
alert(Math.PI); //2  
  
var b = (Math.PI++);   
alert(b); //3  
alert(Math.PI); //4  
  
var c = Math.PI = (++Math.PI);   
alert(c); //5  
alert(Math.PI); //6  
  
  
var d = Math.PI = (Math.PI++);   
alert(d); //7  
alert(Math.PI); //8  
  
  
var e = Math.PI = (Math.PI + 1);  
alert(e); //9  
alert(Math.PI); //10  

对于相关的运行需要注意的是:
1.Math.PI有ReadOnly属性,不能被修改。在其他语言中尝试修改会报错,但javascript这斯不会告诉你不能这么干滴,所以你改了也没用。于是2、4、6、8结果都是 3.141592653589793

2.那么1呢,不是说好Math.PI不会变的么?这得从规范来理解:

11.4.4 Prefix Increment Operator The production UnaryExpression :

++ UnaryExpression is evaluated as follows:
1.Evaluate UnaryExpression.
2.Call GetV alue(Result(1)).
3.Call ToNumber(Result(2)).
4.Add the value 1 to Result(3), using the same rules as for the + operator (see 11.6.3).
5.Call PutV alue(Result(1), Result(4)).
6.Return Result(4).

重点在于返回的是自增后的值。
于是1值为4.141592653589793。

3则返回自增前的值为3.141592653589793

3.赋值操作符

11.13.1 Simple Assignment ( = )
The production AssignmentExpression : LeftHandSideExpression = AssignmentExpression is evaluated as follows:
1. Evaluate LeftHandSideExpression.
2. Evaluate AssignmentExpression.
3. Call GetValue(Result(2)).
4. Call PutValue(Result(1), Result(3)).
5. Return Result(3).

操作符具有右结合性,赋值后,返回第三步的结果,即语句右边的表达式的结果。
也可以直接说连续赋值运算只返回最右边的值,而不管赋值中变量是否发生了变化
于是
5为4.141592653589793
7为3.141592653589793
9为4.141592653589793

http://yiminghe.iteye.com/blog/486649

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>