Increment and decrement operators Overview
If necessary to repeatedly add or subtract a variable number, you can increment (+) and decrement (-) operator to complete.
在 JavaScript 中,递增(++)和递减( -- )既可以放在变量前面,也可以放在变量后面。放在变量前面时,我们可以称为前置递增(递减)运算符,放在变量后面时,我们可以称为后置递增(递减)运算符。
注意:递增和递减运算符必须和变量配合使用。
Increment operator
Pre-increment operator postincrement operator, when used alone, the same.
Pre-increment operator
Use formulas: the first from Canada, the return value
++num 前置递增,就是自加1,类似于 num = num + 1,但是 ++num 写起来更简单。
使用口诀:**先自加,后返回值**
var num = 10;
alert(++num + 10); // 21
// 1. 想要一个变量自己加1 num = num + 1 比较麻烦
var num = 1;
num = num + 1; // ++num
num = num + 1;
console.log(num); // 3
// 2. 前置递增运算符 ++ 写在变量的前面
var age = 10;
++age; // 类似于 age = age + 1
console.log(age); // 11
// 3. 先加1 后返回值
var p = 10;
console.log(++p + 10); // 21
Post-increment operator
After num ++ incrementation is self plus one, like num = num + 1, but num ++ much easier to write.
Use formulas: first return to the original value, after the self-imposed .
var num = 10;
num++; // num = num + 1 ++num;
console.log(num); // 11
// 1. 前置自增和后置自增如果单独使用 效果是一样的
// 2. 后置自增 口诀:先返回原值 后自加1
var age = 10;
// age++ + 10:age++:是一个表达式,先返回这个表达式的值10, 10 + 10 = 20。然后age再加1。
console.log(age++ + 10); // 20
console.log(age); // 11
demo:前置递增、后置递增练习
var a = 10;
++a; // ++a 11 a = 11
var b = ++a + 2; // a = 12 ++a = 12
console.log(b); // 14
var c = 10;
c++; // c++ 11 c = 11
var d = c++ + 2; // c++ = 11 c = 12
console.log(d); // 13
var e = 10;
var f = e++ + ++e; // 1. e++ = 10 e = 11 2. e = 12 ++e = 12
console.log(f); // 22
// 后置自增 先表达式返回原值 后面变量再自加1
Pre-increment and post-increment Summary
Pre-increment and post-increment operator can simplify the preparation of the code, so that the variable value + 1 is simpler than before wording
When used alone, the same operation results
And when combined with other code, the results will be different
Rear: first original value calculation, since the addition (after ancestors hexyl)
Front: the first increase since, after the operation (first has descendants)
When developed, mostly using post increment / decrement, and an exclusive line of code, for example: num ++; or num--.