码迷,mamicode.com
首页 > 编程语言 > 详细

【笔记】JavaScript编码规范- 类型分配&强制转换

时间:2015-05-19 14:47:52      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:javascript

执行强制类型转换语句。

String

// bad <p>// => this.reviewScore = 9;</p>
var A= this.reviewScore + '';


// good
var totalScore = '' + this.reviewScore;


// bad
var totalScore = '' + this.reviewScore + ' total score';


// good
var totalScore = this.reviewScore + ' total score';


使用parseInt对Numbers进行转换,并带一个进制作为参数

var A= '4';

// bad
var val = new Number(A);

// bad
var val = +A;

// bad
var val = A>> 0;

// bad
var val = parseInt(A);

// good
var val = Number(A);


// good
var 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 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
Booleans:

var age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var 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编码规范- 类型分配&强制转换

标签:javascript

原文地址:http://blog.csdn.net/princeterence/article/details/45843767

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!