如何在使用setInterval()更新的值中添加逗号

How to Add commas to Values being updated with setInterval()

本文关键字:添加 更新 setInterval      更新时间:2024-05-12

我有一个脚本,可以计算每秒有多少只小狗和小猫。它使用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);

您可以尝试使用此函数:

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

更新jsFiddle演示