js中怎么格式化一位数变成两位数

比如我要输出的是time=8,怎么让它 变成08呢?

阅读 26.7k
5 个回答
function fix(num, length) {
  return ('' + num).length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : '' + num;
}

fix(1234, 8);
// "00001234"
fix(1234, 2);
// "1234"
var time = 4;
console.log((Array(2).join(0)+time).slice(-2));
if ( num < 10) {
    return "0" + num;
}
新手上路,请多包涵

这是我自己做的程序里进行格式化的方法

let timestamp = new Date()
let time = ("0"+timestamp.getHours()).slice(-2)+':'+("0"+timestamp.getMinutes()).slice(-2)

码diao话不多 ("0" + num).slice(-2)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题