JavaScript 加号(+)运算符号


一,对于引用类型对象(我指的是String,Date,Object,Array,Function,Boolean)的+运算符运算过程如下!
1,首先调用此对象的valueOf方法,得到返回数值A
2,然后把此数值A转换成数字,得到的是最终数值

我的测试如下:
复制代码 代码如下:

function w(s){
document.writeln("<br/>");
document.writeln(s);
document.writeln("<br/>-----------------------------");
}
String.prototype.valueOf=function(){return 1;};
w(+new String("sss"));//输出1
String.prototype.valueOf=function(){return "a";};
w(+new String("sss"));//输出NaN


Date.prototype.valueOf=function(){return 1;};
w(+new Date());//输出1
Date.prototype.valueOf=function(){return "a";};
w(+new Date());//输出NaN

Object.prototype.valueOf=function(){return 1;};
w(+{});//输出1
Object.prototype.valueOf=function(){return "a";};
w(+{});//输出NaN

Array.prototype.valueOf=function(){return 1;};
w(+[]);//输出1
Array.prototype.valueOf=function(){return "a";};
w(+[]);//输出NaN

var s=function(){};
Function.prototype.valueOf=function(){return 1;};
w(+s);//输出1
Function.prototype.valueOf=function(){return "a";};
w(+s);//输出NaN

Boolean.prototype.valueOf=function(){return 1;};
w(+new Boolean());//输出1
Boolean.prototype.valueOf=function(){return "a";};
w(+new Boolean());//输出NaN

二,对于基本数据数据类型,其值转换成数字
复制代码 代码如下:

w(+5);//输出5
w(+true);//输出1
w(+false);//输出0
w(+"ss");//输出NaN
w(+"111");//输出111

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3