增加字符串的数字位数(0,1,2,...,9,00,01)

时间:2013-10-10 16:16:29

标签: javascript string node.js numbers counting

我需要JavaScript中的一个函数(用于Node),它会增加字符串中的数字,如下所示:

"0", "1", "2", "3", ..., "8", "9", "00", "01", "02"

等等。我该怎么做呢?我可以想到很多条件,但这可能不会达到最佳状态。


到目前为止我所拥有的:

var count = "0";

function increment() {
    var number = parseInt(count), digits = count.length;
    var upDigit = true;
    for (var i = 0; i < digits; i++) {
        if (i !== 9)
            upDigit = false;
    }
    if (upDigit) {
        var zeros = "";
        for (var i = 0; i <= digits; i++) {
            zeros += "0";
        }
        count = zeros;
    } else {
        count = number++;
    }
}

5 个答案:

答案 0 :(得分:2)

根据我之前的回答:

function range(i, to) {
    var v,
        r = [],
        s = to,
        e = i.length,
        t = Math.pow(10, e),
        l = (t + '').length;
    i = parseInt(i);
    to = Math.pow(10, to.length);
    for (; i <= to; i++) {
        if (i === t) {
            i = 0;
            t = Math.pow(10, ++e);
            l = (t + '').length;
        }
        v = new Array(l - (i + '').length).join('0') + i;
        r.push(v);
        if (v === s) { break; }
    }
    return r;
}

用法示例:

console.log(range('05', '15').join()); // "05,06,07,08,09,10,11,12,13,14,15"

答案 1 :(得分:1)

function zeroPad(str, ln){
  if(str.length > ln){ raise('Trying to zero pad a too-long string') };
  var out = str;
  while(out.length !== ln){
    out = '0'+out;
  };
  return out;
}

function iterate(previous, final){
  console.log(previous);
  if(previous === final){ return };
  var next = "";
  var ln = previous.length; // how many characters so far
  // use a regex to test if every character is 9
  var nines = 
    previous.match(/^9+$/) ? true : false;
  if(nines){
    for(var i=0; i<ln+1; i++){
      next += "0";
    }
    return iterate(next, final);
  } else {
    var value = +previous; // coerce to number
    value += 1;
    next = zeroPad(String(value), ln)
    return iterate(next, final);
  }
};

iterate("0", "000");

答案 2 :(得分:1)

这是你期待的结果吗?

var e = 0,
    t = 0,
    l = 0,
    i = 0;
for (; i <= 100; i++) {
    if (i >= t) {
        i = 0;
        t = Math.pow(10, ++e);
        l = (t + '').length;
    }
    console.log(new Array(l - (i + '').length).join('0') + i);
}

填充方法:

new Array(2).join('0') == ['', ''].join('0') == '0'; // true

答案 3 :(得分:0)

function pad(num) {
  return num > 0 ? pad(num-1) + "0" : ""; 
}

function add(str) {
    var len, num, numlen;
    len = str.length;
    num = +str;
    numlen = String(num).length;
    if (/^9+$/.test(num)) { return pad(len + 1); }
    else { return pad(len - numlen) + String(num + 1); }
}

add('0078') // '0079'
add('0099') // '00000'

fiddle

答案 4 :(得分:-2)

嗯,你可以先尝试将字符串转换成一个整数然后递增1然后按如下方式返回字符串:

function incrementString(string){
    var number = parseInt(string);
    number++;
    return number.toString();
}