如何修改此代码以在任何低于10的数字之前添加0

$('#detect').html( 至Geo(apX, screenX)  + latT +', '+ 至Geo(apY, screenY) + lonT  );

function 至Geo(d, max) {
   var c = '';

   var r = d/max * 180;
   var deg = Math.floor(r);
   c += deg + "° ";

   r = (r - deg) * 60;
   var min = Math.floor(r);
   c += min + "′ ";

   r = (r - min) * 60;
   var sec = Math.floor(r);
   c += sec + "″";

   return c;
}

So the outpout would change from

4° 7′ 34″W, 168° 1′ 23″N

04° 07′ 34″W, 168° 01′ 23″N

Thanks for your time

推荐答案

你总能做到

('0' + deg).slice(-2)

See slice():

也可以使用负数从数组末尾进行 Select

Hence

('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2)  // '04'

For ease of access, you could of course extract it to a function, or even extend Number with it:

Number.prototype.pad = function(n) {
    return new Array(n).join('0').slice((n || 2) * -1) + this;
}

Which will allow you to write:

c += deg.pad() + '° '; // "04° "

上述函数pad接受指定所需字符串的长度的自变量.如果未使用此类参数,则默认为2.您可以编写:

deg.pad(4) // "0045"

请注意明显的缺点,n的值不能大于11,因为0的字符串目前只有10个字符长.这当然可以给出一个技术解决方案,但我不想在这样一个简单的函数中引入复杂性.(如果你 Select 这样做,请参阅alex's answer以了解一个很好的方法).

Note also that you would not be able to write 2.pad(). It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.

Jquery相关问答推荐

为什么如果使用转换规模,juserui可拖动遏制不起作用

退出 jquery.each 循环后

jQuery中的多个 Select 器链接?

何时执行 $(document).ready 回调?

.slice(0) 在这里有什么意义?

JQuery/Javascript:判断 var 是否存在

错误找不到 jquery-2.0.2.min.map

使用 jQuery click 处理锚点 onClick()

在 contenteditable div 中的插入符号处插入 html

使用 jQuery 从 AJAX 响应(json)构建表行

自动完成将值而不是标签应用于文本框

将打开/关闭图标添加到 Twitter Bootstrap 可折叠项(手风琴)

隐藏 div 但保留空白

Underscore.js 和 jQuery 互补吗?

如何在页面加载时启动 jQuery Fancybox?

将数据发布到 JsonP

在某个点停止固定位置滚动?

使用 jQuery 和 CSS 将数字转换为星级显示

请求的资源错误中不存在Access-Control-Allow-Origin标头

使用 moment.js 将日期转换为字符串MM/dd/yyyy