ECMAScript定义了5个算数运算符:加减乘除取余.如果参与算数运算的值不是数值,那么后台会先使用Number()转型函数将其转换为数值(隐式转换).
运算规则如下:
(1).数值直接进行算数操作.
(2).只要有一个操作数是NaN结果即为NaN.
(3)
例子:
1.加法
var box = 1 + 2; //等于3
var box = 1 + NaN; //NaN,只要有一个NaN就为NaN
var box = Infinity + Infinity; //Infinity
var box = -Infinity + -Infinity; //-Infinity
var box = Infinity + -Infinity; //NaN,正无穷和负无穷相加等NaN
var box = 100 + '100'; //100100,字符串连接符,有字符串就不是加法
var box = '您的年龄是:' + 10 + 20; //您的年龄是:1020,被转换成字符串
var box = 10 + 20 + '是您的年龄'; //30是您的年龄,没有被转成字符串
var box = '您的年龄是:' + (10 + 20); //您的年龄是:30,没有被转成字符串
var box = 10 + 对象 //10[object Object],如果有toString()或valueOf()
则返回10+返回数的值
2.减法
var box = 100 - 70; //等于30
var box = -100 - 70 //等于-170
var box = -100 - -70 //-30,一般写成-100 - (-70)比较清晰
var box = 1 - NaN; //NaN,只要有一个NaN就为NaN
var box = Infinity - Infinity; //NaN
var box = -Infinity - -Infinity; //NaN
var box = Infinity - -Infinity; //Infinity
var box = -Infinity - Infinity; //-Infinity
var box = 100 - true; //99,true转成数值为1
var box = 100 - ''; //100,''转成了0
var box = 100 - '70'; //30,'70'转成了数值70
var box = 100 - null; //100,null转成了0
var box = 100 - 'Lee'; //NaN,Lee转成了NaN
var box = 100 - 对象 //NaN,如果有toString()或valueOf()
则返回10-返回数的值
3.乘法
var box = 100 * 70; //7000
var box = 100 * NaN; //NaN,只要有一个NaN即为NaN
var box = Infinity * Infinity; //Infinity
var box = -Infinity * Infinity ; //-Infinity
var box = -Infinity * -Infinity ; //Infinity
var box = 100 * true; //100,true转成数值为1
var box = 100 * ''; //0,''转成了0
var box = 100 * null; //0,null转成了0
var box = 100 * 'Lee'; //NaN,Lee转成了NaN
var box = 100 * 对象 //NaN,如果有toString()或valueOf()
则返回10 - 返回数的值
4.除法
var box = 100 / 70; //1.42....
var box = 100 / NaN; //NaN
var box = Infinity / Infinity; //NaN
var box = -Infinity / Infinity ; //NaN
var box = -Infinity / -Infinity; //NaN
var box = 100 / true; //100,true转成1
var box = 100 / ''; //Infinity,
var box = 100 / null; //Infinity,
var box = 100 / 'Lee'; //NaN
var box = 100 / 对象; //NaN,如果有toString()或valueOf()
则返回10 / 返回数的值
5.求模
var box = 10 % 3; //1,余数为1
var box = 100 % NaN; //NaN
var box = Infinity % Infinity; //NaN
var box = -Infinity % Infinity ; //NaN
var box = -Infinity % -Infinity; //NaN
var box = 100 % true; //0
var box = 100 % ''; //NaN
var box = 100 % null; //NaN
var box = 100 % 'Lee'; //NaN
var box = 100 % 对象; //NaN,如果有toString()或valueOf()
则返回10 % 返回数的值