特别说明:转载与网络:https://github.com/adamlu/javascript-style-guide
- 在语句的开始执行类型转换.
-
字符串:
// => this.reviewScore = 9; // bad var totalScore = this.reviewScore + ''; // good var totalScore = '' + this.reviewScore; // bad var totalScore = '' + this.reviewScore + ' total score'; // good var totalScore = this.reviewScore + ' total score';
-
对数字使用
parseInt并且总是带上类型转换的基数.var inputValue = '4'; // bad var val = new Number(inputValue); // bad var val = +inputValue; // bad var val = inputValue >> 0; // bad var val = parseInt(inputValue); // good var val = Number(inputValue); // good var val = parseInt(inputValue, 10); // 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;
-
布尔值:
var age = 0; // bad var hasAge = new Boolean(age); // good var hasAge = Boolean(age); // good var hasAge = !!age;
本文详细介绍了在JavaScript中进行不同类型转换的最佳实践,包括字符串、数字和布尔值的正确转换方式,帮助开发者避免常见的陷阱和提高代码效率。
803

被折叠的 条评论
为什么被折叠?



