Javascript method to implement arithmetic addition: 1. Use the " " operator, syntax "a b"; 2. Use the "=" operator, syntax "a = b"; 3. Use " " increment operation symbol, syntax "a" or "a".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to implement addition operation in javascript
Method 1: Use the " " operator
Example 1: Pay attention to the summation operation of special operands
var n = 5; //定义并初始化任意一个数值 console.log(NaN + n); //NaN与任意操作数相加,结果都是NaN console.log(Infinity + n); //Infinity与任意操作数相加,结果都是Infinity console.log(Infinity + Infinity); //Infinity与Infinity相加,结果是Infinity console.log((-Infinity) + (-Infinity)); //负Infinity相加,结果是负Infinity console.log((-Infinity) + Infinity); //正负Infinity相加,结果是NaN
Example 2: The addition operator can determine whether it is an addition operation or a connection operation based on the data type of the operands
console.log(1 + 1); //如果操作数都是数值,则进行相加运算 console.log(1 + "1"); //如果操作数中有一个是字符串,则进行相连运算 console.log(3.0 + 4.3 + ""); //先求和,再连接,返回"7.3" console.log(3.0 + "" + 4.3); //先连接,再连接,返回"34.3" //3.0转换为字符串3
Note: In When using the addition operator, you should first check whether the data type of the operand meets the requirements.
Method 2: Use the "=" operator
The role of the "=" operator: perform an addition operation or connection operation on the right operand before assigning a value, Then copy the operation result to the left operand
var a=1,b=2,c=3,d=4; console.log(a+=b); console.log(b+=a); console.log(c+=b); console.log(d+=d); console.log(a); console.log(b); console.log(c); console.log(d);
Method 3: Use the " " increment operator
Increment
Operation is a simple way to change its own result by continuously adding 1 and then assigning the result to the left operand.
As a unary operator, the increment operator functions on variables, array elements or object properties, and cannot act on direct quantities. According to different positions, it can be divided into 2 operation methods:
Prefix increment (n): increment first and then assign value.
Post-increment (n): assign value first, then increment.
Example:
var a = b = c = 4; console.log(a++); //返回4,先赋值,再递增运算结果不变 console.log(++b); //返回5,先递增,再赋值,运算结果加1 console.log(c++); //返回4,先赋值,再递增,运算结果不变 console.log(c); //返回5,变量的值加1 console.log(++c); //返回6,先递增,再赋值,运算结果加1 console.log(c); //返回6
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to implement arithmetic addition in javascript. For more information, please follow other related articles on the PHP Chinese website!