且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在字符串前添加零

更新时间:2023-11-15 15:34:10

一个简单的一行解决方案,没有任何循环

适用于 IE5-11、Firefox、Chrome 等.假设整数输入.

A simple one line solution without any loops

Works with IE5-11, Firefox, Chrome, etc. Assumes integer input.

 function pad(n) { return ("000000" + n).slice(-6); }

运行代码段进行测试:

<html>
<body>
<input id="stdin" placeholder="enter a number" maxlength="6"><button onclick="test()">Test</button>
<textarea id="stdout" style="width:100%;height:20em;padding:1em;"></textarea>
<script type="text/javascript">
    
   function pad(n) { return ("000000" + n).slice(-6); }
    
   function test() {
       var n = parseInt( document.getElementById('stdin').value);
       var e = document.getElementById('stdout').innerHTML += n + ' = ' + pad(n) + '\n';
   }
 
</script>
</body>
</html>