开发者

JavaScript toString() problem

I just want to ask how to convert the number to String. What I want to output is 开发者_如何学JAVA"000000" incremented per second "0000001". I tried different methods but it will output to 1,2,3... I tried this but still won't work.

 $(document).ready(function(){
  xx();
  var x = 0;

  function xx()
  {

    x++;
    if(x.length==5) {
        x = "00000" + convert.toString(x);
    }

    $("div.sss").text(x);


    setTimeout(xx,1000);
  }

 });


Like this:

function padString(str, size) {
    str = "" + str;
    if (str.length >= size)
        return str;
    return "00000000000000000000000000".substr(0, size - str.length) + str;
}


function xx()
{
    x++;
    str_x = "000000"+x;
    str_x = str_x.substring(str_x.length - 6);
    $("div.sss").text(str_x);
    setTimeout(xx, 1000);
}


Try this

<script>
var x=00000+"";//convert number to string
for(var i=0;i<=5;i++){
var y=x+"0000"+[i];
document.write("<br/>");
document.write(y);
}
</script>

check the link for live working example http://jsfiddle.net/informativejavascript/GmWYr/1/


Since x is Number is will not have a length property so x.length==5 will always evaluate as false so your attempt to prefix it with a series of zeros will never be executed.

If it was executed, then it would fail because convert is undefined.


you don't need to use toString. You can do "foo" + x or "00000" + x directly


This works:

$(document).ready(function() {

 var x = 0;

 function loop() {
  var t = x + "";
  var n = 6 - t.length;

  while (n > 0) {
   t = "0" + t;
   n -= 1;
  }
  $("#foo").text(t);    
  x += 1;   
  setTimeout(loop, 1000);
 }

 loop();

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜