在一些框架中看到了類似這樣的寫法:+new Date();感覺有些怪,查閱了相關(guān)資料和一些網(wǎng)友的幫助.對(duì)此用法解釋如下,希望對(duì)大家有所幫助,不合適的地方請(qǐng)大家指正!
一,對(duì)于引用類型對(duì)象(我指的是String,Date,Object,Array,Function,Boolean)的+運(yùn)算符運(yùn)算過程如下!
1,首先調(diào)用此對(duì)象的valueOf方法,得到返回?cái)?shù)值A(chǔ)
2,然后把此數(shù)值A(chǔ)轉(zhuǎn)換成數(shù)字,得到的是最終數(shù)值
我的測(cè)試如下:
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
二,對(duì)于基本數(shù)據(jù)數(shù)據(jù)類型,其值轉(zhuǎn)換成數(shù)字
w(+5);//輸出5
w(+true);//輸出1
w(+false);//輸出0
w(+"ss");//輸出NaN
w(+"111");//輸出111