标签:
ECMAScript 定义了 5 个算术运算符,加、减、乘、除、求模(取余)。如果在算术运算的值不是数值,那么后台会先使用 Number()转型函数将其转换为数值(隐式转换)。
一、加法
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],最后的类型是string类型,如果有 toString()或 valueOf()则返回 10+返回数的值 var box =10+ { toString:function(){ return 100; } } alert(box);//110
二、减法
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 结果还是100 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()则返回 100-返回数的值 var box = 100 - { toString:function(){ return 10; } }; alert(box);
三、乘法
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()则返回 100 - 返回数的值
四、除法
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,两个数相除,第二个数不能为0 var box = 100 / null; //Infinity, var box = 100 / ‘Lee‘; //NaN var box = 100 / {}; //NaN,如果有 toString()或 valueOf()则返回 100 / 返回数的值
五、求模
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()则返回 100 % 返回数的值
标签:
原文地址:http://www.cnblogs.com/LO-ME/p/4384384.html