类型转换
22.1 在语句开始的时候进行类型转换
22.2 字符串
const totalScore = new String(this.reviewScore);
const totalScore = this.reviewScore + '';
const totalScore = this.reviewScore.toString();
const totalScore = String(this.reviewScore);
22.3 数字:使用Number
来进行类型转换,使用parseInt
的时候带上类型转换的基数
const inputValue = '4';
const val = new Number(inputValue);
const val = +inputValue;
const val = inputValue >> 0;
const val = parseInt(inputValue);
const val = Number(inputValue);
const val = parseInt(inputValue, 10);
22.4 如果因为某些原因 parseInt 成为你所做的事的瓶颈而需要使用位操作解决性能问题时,留个注释说清楚原因和你的目的。
const val = inputValue >> 0;
22.5 注意:小心使用位操作运算符。数字会被当成 64 位值,但是位操作运算符总是返回 32 位的整数(参考)。位操作处理大于 32 位的整数值时还会导致意料之外的行为。关于这个问题的讨论。最大的 32 位整数是 2,147,483,647:
2147483647 >> 0;
2147483648 >> 0;
2147483649 >> 0;
22.6 布尔值
const age = 0;
const hasAge = new Boolean(age);
const hasAge = Boolean(age);
const hasAge = !!age;