Skip to content

i++和++i的区别 #62

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
funnycoderstar opened this issue Jan 3, 2019 · 0 comments
Open

i++和++i的区别 #62

funnycoderstar opened this issue Jan 3, 2019 · 0 comments

Comments

@funnycoderstar
Copy link
Owner

funnycoderstar commented Jan 3, 2019

++是递增操作符, 使用时可以分为前置型和后置型, ++i是前置型, i++是后置型;
后置型和前置型最大的区别是:

  • 前置操作, 变量的值都是在语句被求值前改变的
  • 后置操作, 是在包含它们的语句被求值之后才执行的

可以看下面几个例子

例1:

var age = 29;
++age; // 30

var num1 = 29;
num1++; // 30

把递增操作符放在变量后面并不会改变语句的结果, 因为递增是这条语句的唯一操作, 但是, 当语句中还包含其他操作时, 上面的区别就会非常明显了;

例2

var num1 = 2;
var num2 = 20;
var num3 = --num1 + num2; // 21
var num4 = num1 + num2; // 21

这里num3值所以等于21, 是因为num1先减了1再与num2相加, 而变量num4也等于21是因为相应的加法操作使用了num1减去1之后的值;

var num1 = 2;
var num2 = 20;
var num3 = num1-- + num2; // 22
var num4 = num1 + num2; // 21

这里仅仅将前置递减改成了后置递减, 就可以看到差别,在前面使用前置递减的例子中, num3和num4都等于21. 而在这个例子中, num3等于22, num4等于21. 差别的根源在于, 这里在计算num3时使用了num1的原始值2完成了加法计算, 而num4则使用了递减后的值

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant