【筆記】JavaScript編碼規範- 類型分配&強制轉換

來源:互聯網
上載者:User

標籤:javascript

執行強制類型轉換語句。

String

// bad <p>// => this.reviewScore = 9;</p>var A= this.reviewScore + '';// goodvar totalScore = '' + this.reviewScore;// badvar totalScore = '' + this.reviewScore + ' total score';// goodvar totalScore = this.reviewScore + ' total score';


使用parseInt對Numbers進行轉換,並帶一個進位作為參數

var A= '4';// badvar val = new Number(A);// badvar val = +A;// badvar val = A>> 0;// badvar val = parseInt(A);// goodvar val = Number(A);// goodvar val = parseInt(A, 10);


無論出於什麼原因,或許你做了一些”粗野”的事;或許parseInt成了你的瓶頸;或許考慮到效能,需要使用位元運算,都要用注釋說明你為什麼這麼做
// good/*** parseInt was the reason my code was slow.* Bitshifting the String to coerce it to a* Number made it a lot faster.*/var val = inputValue >> 0;

注意:當使用位元運算時,Numbers被視為64位值,但是位元運算總是返回32位整型(source)。對於整型值大於32位的進行位元運算將導致不可預見的行為。Discussion.最大的有符號32位整數是2,147,483,647

2147483647 >> 0 //=> 21474836472147483648 >> 0 //=> -21474836482147483649 >> 0 //=> -2147483647
Booleans:

var age = 0;// badvar hasAge = new Boolean(age);// goodvar hasAge = Boolean(age);// goodvar hasAge = !!age;


1:14 And God said,Let there be lights in the firmament of the heaven to divide the day from the night;and let them be for signs,and for seasons,and for days,and years:



【筆記】JavaScript編碼規範- 類型分配&強制轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.