2012-12-13 70 views

回答

2
function get3DigitStr(num) { 
    if (num > 99) return num + ""; 
    var s = "00" + num; 
    return s.substr(-3); 
} 
1

pad(number,length)函數需要一個數字和填充量來添加它。然後循環n次,每次加0,直到長度滿足。

function pad(number, length) { 
     var str = '' + number; 
     while (str.length < length) { 
     str = '0' + str; 
     } 
     return str; 
    } 

    var results = []; 

    for(var i = 0; i < 999; i++){ 
     results[i] = pad(i,3); 
    } 

    console.log(results); 
      /* Outputs ["001","002","003","004", "005", "006","007","011","012","013","014","015","111","222", "333"]*/ 
+0

thx很詳細 – user1871516

+0

@ user1871516很高興我可以幫忙。 –

1

試試這個:

var value 
while ((value+"").length < 3) 
    value = "0" + value; 
document.write(value); 
1

試試這個功能:

function add(value) { 
    return value.length < 3 ? add("0"+value) : value 
} 

下面是一些例子:

var newvalue = add("1"); //newvalue = "001" 
var newvalue = add("21"); //newvalue = "021" 
var newvalue = add("999"); //newvalue = "999" 

你可以在這裏測試:DEMO