gpt4 book ai didi

javascript - 如何通过JS在我的递增数字中添加逗号?

转载 作者:行者123 更新时间:2023-12-02 17:37:20 26 4
gpt4 key购买 nike

我正在尝试在 20000 之间添加一个逗号以显示为 20,000,而不会弄乱并且已经非常接近,但正在尝试填写后续步骤。下面,我列出了我的代码以及能够执行此操作的函数,但尝试将两者连接在一起以正常工作。

Here is my jsFiddle!

还有代码..

HTML

<span id="liveNumbers">23000</span>

JS

setInterval(function(){
random = (Math.floor((Math.random()*2)+1));
var plus = Math.random() < 0.5 ? 1 : 1;
random = random * plus;
currentnumber = document.getElementById('liveNumbers');

document.getElementById('liveNumbers').innerHTML = parseInt(currentnumber.innerHTML) + random;

}, 3000);

function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}

最佳答案

您必须更改初始值以包含逗号或在 setInterval 开始之前执行初始运行,但类似这样的操作可能会起作用:

setInterval(function(){
random = (Math.floor((Math.random()*2)+1));
var plus = Math.random() < 0.5 ? 1 : 1;
random = random * plus;
currentnumber = document.getElementById('liveNumbers');
var curnum = parseInt(currentnumber.innerHTML.replace(",",""));

document.getElementById('liveNumbers').innerHTML =
commaSeparateNumber(curnum + random);
}, 3000);

function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}

关于javascript - 如何通过JS在我的递增数字中添加逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22492738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com