如何向 Javascript 计数器添加逗号?
How do I add commas to this Javascript counter?
我是 JS 的初学者,不知道如何在这里完成它。想法是在数字中使用逗号,以便在计数时更容易阅读,并且最终的静态结果也应该使用逗号。
例如:“10,000”
var a = 0;
$(window).scroll(function() {
var oTop = $('#counter').offset().top - window.innerHeight;
if (a == 0 && $(window).scrollTop() > oTop) {
$('.counter-value').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 2000,
easing: 'swing',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
a = 1;
}
});
最好的方法是使用内置的 Intl 对象。更多信息 here.
const number = 123456;
const formattedNumber = new Intl.NumberFormat('en-us').format(number);
console.log({ formattedNumber }); // 123,456
我是 JS 的初学者,不知道如何在这里完成它。想法是在数字中使用逗号,以便在计数时更容易阅读,并且最终的静态结果也应该使用逗号。
例如:“10,000”
var a = 0;
$(window).scroll(function() {
var oTop = $('#counter').offset().top - window.innerHeight;
if (a == 0 && $(window).scrollTop() > oTop) {
$('.counter-value').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 2000,
easing: 'swing',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
a = 1;
}
});
最好的方法是使用内置的 Intl 对象。更多信息 here.
const number = 123456;
const formattedNumber = new Intl.NumberFormat('en-us').format(number);
console.log({ formattedNumber }); // 123,456