如何使用setInterval()更新要更新的值的逗号

时间:2013-12-09 17:43:01

标签: javascript jquery

我有一个脚本可以计算每秒钟(小狗和小猫)的数量。它使用Date()来计算在本月初和月初生成的数量。但我在更新此脚本时遇到困难,无法在数千,数百万,数十亿的标记处添加逗号。有人可以告诉我在这个脚本中添加逗号的最佳方法吗?

这里是jsFiddle

var start = new Date(),
    midnight = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0),
    first = new Date(start.getFullYear(), start.getMonth(), 1);

var now = new Date(),
    secondsFromStart = Math.floor((now - start)/1000),
    secondsFromMidnight = Math.floor((now - midnight)/1000),
    secondsFromFirst = Math.floor((now - first)/1000);

var elems = [];
$(".s").each(function(){
    var $this = $(this);
    var BornPerSec = $this.data("quantity"),
        Start = secondsFromStart*BornPerSec,
        Midnight = secondsFromMidnight*BornPerSec,
        First = secondsFromFirst*BornPerSec;
    elems.push({
        obj: $this,
        BornPerSec: BornPerSec,
        Start : Start,
        Midnight : Midnight,
        First : First,       
        now: $this.children('.now'),
        morning: $this.children('.morning'),
        month: $this.children('.month'),
     });
});
setInterval(function () {
    $.each(elems,function(i,n){
        n.Start+=n.BornPerSec;
        n.Midnight+=n.BornPerSec;
        n.First+=n.BornPerSec;
        n.now.text(n.Start % 1 === 0 ?n.Start: n.Start.toFixed(2));
        n.morning.text(n.Midnight % 1 === 0 ?n.Midnight:n.Midnight.toFixed(2));
        n.month.text(n.First % 1 === 0 ?n.First:n.First.toFixed(2));
    });
}, 1000);

1 个答案:

答案 0 :(得分:1)

您可以尝试使用此功能:

function numberWithCommas( x ) {
    return x.toString().replace( /\B(?=(\d{3})+(?!\d))/g, ',');
}

Updated jsFiddle demo