zoukankan      html  css  js  c++  java
  • 笔记-赋值与运算的顺序

    var i=1;
    i=i++;
    alert(i);

    为什么i=1?

    ------------------------------------------------------------------------------------------------------------------------------

    ECMAScript® Language Specification

    11.13.1 Simple Assignment ( = )

    The production AssignmentExpression : LeftHandSideExpression =
    AssignmentExpression is evaluated as follows:

    Let lref be the result of evaluating LeftHandSideExpression. Let rref
    be the result of evaluating AssignmentExpression. Let rval be
    GetValue(rref).
     Throw a SyntaxError exception if the following
    conditions are all true: Type(lref) is Reference is true
    IsStrictReference(lref) is true Type(GetBase(lref)) is Environment
    Record GetReferencedName(lref) is either "eval" or "arguments" Call
    PutValue(lref, rval).
     Return rval. NOTE When an assignment occurs
    within strict mode code, its LeftHandSide must not evaluate to an
    unresolvable reference. If it does a ReferenceError exception is
    thrown upon assignment. The LeftHandSide also may not be a reference
    to a data property with the attribute value {[[Writable]]:false}, to
    an accessor property with the attribute value {[[Set]]:undefined}, nor
    to a non-existent property of an object whose [[Extensible]] internal
    property has the value false. In these cases a TypeError exception is
    thrown.

    注意這兩句:

    Let rval be GetValue(rref).
    Call PutValue(lref, rval).

    也就是說,首先執行 i++,此時 i 被賦值 2,並返回 1,然後再賦值 1 給 i,最終 i 爲 1。

    簡單地說,

    var i = 1;
    i = i++;
    

    等價於

    var i, temp; // temp is "rval", which may not be an actual variable. 
    i = 1;
    temp = i;
    i = i + 1;
    i = temp;
    我的github: https://github.com/moux1024
  • 相关阅读:
    linux下安装vsftp
    CentOS 7.0编译安装Nginx1.6.0+MySQL5.6.19+PHP5.5.14
    Centos编译安装PHP 5.5笔记
    centos使用更新更快的yum源
    使用Android Studio搭建Android集成开发环境
    设计模式(三)原型模式
    overridePendingTransition
    Android手势密码实现
    UserInfoActivity用户图像修改和退出登录
    设计模式(二)建造者模式
  • 原文地址:https://www.cnblogs.com/xd1024/p/4637649.html
Copyright © 2011-2022 走看看