Possible Duplicate:
Is there a JavaScript function that can pad a string to get to a determined length?
如何在不使用任何 3rd 方库的情况下将 JavaScript 中的 convert '1' 转换为 '0001'。我在 php 中使用 spritf 完成了此操作: $time = sprintf('%04.0f',$time_arr[$i]);
最佳答案
这是一个聪明的小把戏(我想我以前在 SO 上见过):
var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str
如果 substring 的第二个参数是负数,JavaScript 比某些语言更宽容,所以它会“正确溢出”(或不正确,取决于它的查看方式):
也就是说,有了上面的:
- 1 -> “0001”
- 12345 -> “12345”
支持负数作为练习;-)
关于javascript - 在 JavaScript 中将 '1' 转换为 '0001',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5366849/