標籤: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編碼規範- 類型分配&強制轉換