gpt4 book ai didi

javascript - 在此示例中,如何在 Javascript 中添加分隔千位的空格

转载 作者:行者123 更新时间:2023-11-30 10:17:11 25 4
gpt4 key购买 nike

我这里有两个函数。一个添加“,”用于分隔千位的函数,例如 1234 -> 1 234。还有一个用于递增的函数。

增加的功能只是打印 123456,我想将它们结合起来,虽然我可以更改:

$this.html(++current);

到:$this.html(addSpaces(++current));

但它不起作用。请帮助我,我该如何解决这个问题?

function addSpaces(nStr)
{
nStr += "";
x = nStr.split(".");
x1 = x[0];
x2 = x.length > 1 ? "." + x[1] : "";
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, "$1" + " " + "$2");
}
return x1 + x2;
}


function count($this) {

var current = parseInt($this.html(), 10);
current = current + 13 /* This is increment */

$this.html(++current);
if (current > $this.data("count")) {
$this.html($this.data("count"));
} else {
setTimeout(function() { count($this); }, 100);
}

}

最佳答案

更新 我修改了你的 jsfiddle

由于 current 将根据您的格式化值一次又一次地进行解析,因此我们需要从中删除空格

current = parseInt(($this.html()).split(' ').join(''), 10)

此外,您需要在名为 nextString 的变量下跟踪递增的 current 的字符串值

您希望您的号码最多按 3 位数字分组。问题是,如果 3 不能整除字符串的长度,您可能会有一个 remainder。分离字符串的 remainder 部分(最左边)后,您可以将所有其他部分按 3 进行分组。

DEMO

function addSpaces(nStr)
{
var remainder = nStr.length % 3;
return (nStr.substr(0, remainder) + nStr.substr(remainder).replace(/(\d{3})/g, ' $1')).trim();
}

function count($this) {

var current = parseInt(($this.html()).split(' ').join(''), 10),
nextString = (current+13) + '';

$this.html(addSpaces(nextString));

if (current > $this.data("count")) {
$this.html($this.data("count"));
} else {
setTimeout(function() {
count($this);

}, 100);
}

}

关于javascript - 在此示例中,如何在 Javascript 中添加分隔千位的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23149669/

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