Javascript中的加號(+)運算子

來源:互聯網
上載者:User

在一些架構中看到了類似這樣的寫法:+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 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.