在一些架構中看到了類似這樣的寫法:+new Date();感覺有些怪,查閱了相關資料和一些網友的協助.對此用法解釋如下,希望對大家有所協助,不合適的地方請大家指正!
一,對於參考型別對象(我指的是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