将逗号添加到javascript计数计时器

时间:2011-08-07 03:52:46

标签: javascript timer comma

这是我的计划:

<script>
var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

function countup(yr, m, d) {
    var today = new Date()
    var todayy = today.getYear()
    if (todayy < 1000) todayy += 1900
    var todaym = today.getMonth()
    var todayd = today.getDate()
    var todaystring = montharray[todaym] + " " + todayd + ", " + todayy
    var paststring = montharray[m - 1] + " " + d + ", " + yr
    var difference = (Math.round((Date.parse(todaystring) - Date.parse(paststring)) / (24 * 60 * 60 * 1000)) * 1)
    difference += ""
    document.write("" + difference + "")
}
//enter the count up date using the format year/month/day
countup(2007, 01, 24)
</script>

我正在尝试在数千个位置输出插入逗号(例如1,234而不是1234)。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

要为每三分之一添加逗号,只需从后面和每三分之一迭代转换为字符串的数字,添加逗号。

var str = "" + num;
var s2 = "";
for( var i = str.length()-1; i != 0; i-- ){
    s2 += str.charAt(i);
    if( 0 == (str.length() - i) % 3 )
        s2 += ",";
}

或者这样。不确定数学。