Sam*_*ole 28 javascript jslint
我总是通过向它们添加一个空字符串将数字转换为字符串:
var string = 1 + '';
但是,JSLint抱怨这种方法Expected 'String' and instead saw ''''.,看起来确实有些难看.
有没有更好的办法?
Sea*_*ira 22
我相信JSLint批准的方式是拨打.toString()号码:
var stringified = 1..toString();
// Note the use of the double .. to ensure the the interpreter knows
// that we are calling the toString method on a number --
// not courting a syntax error.
// You could also theoretically call 1["toString"];
Run Code Online (Sandbox Code Playgroud)
(对不起,上面的评论可能会更好,但我还没有获得发表评论的权利,所以...)
请记住,jslint不只是验证您的JavaScript是否实际运行,它还试图强制执行编码样式,以帮助您生成更易读和可维护的代码.
所以1 + '' 工作,但不一定是每个人最可读的选项,而显式的选择(见其他答案)对每个人都应该是可读的.当然,如果没有其他人能够看到你的代码,你只需要担心,如果你下个月或明年回来,你是否能够理解它...
不要忘记以下两个语句不会产生相同的结果:
var s1 = 1 + 3 + ''; // gives '4'
var s2 = '' + 1 + 3; // gives '13'
Run Code Online (Sandbox Code Playgroud)
我认为1 + ''这只是讨论的简化,或者为什么不'1'首先使用?
| 归档时间: |
|
| 查看次数: |
4313 次 |
| 最近记录: |