【笔记】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:



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值