我想要实现的是从一个简单的字符串输入创建一个带有千位定界符的格式化数字。
所以我的输入看起来像 let input = "12345"
而我预期的返回值应该像 "12,345"
。
我知道已经有几个库可以处理这个问题,但我想保持简单,我自己来做。我当前的解决方案有点多余(因为双重 .reverse()
),我很确定,有更好的解决方案。
let array = input.split('');
array.reverse();
for (let i = 3; i < array.length; i += 4) {
array.splice(i, 0, ',');
}
array.reverse();
return array.join('');
最佳答案
我对另一个问题做了类似的回答:Insert new element after each nt-h array elements。这是一种通用方法,每 N
位置插入一个 token 。该解决方案使用带有 Array.splice() 方法的 while
循环。为了满足您的要求,我扩展了它以支持从数组末尾开始插入。只是另一种选择...
let insertTokenEveryN = (arr, token, n, fromEnd) => {
// Clone the received array, so we don't mutate the
// original one. You can ignore this if you don't mind.
let a = arr.slice(0);
// Insert the <token> every <n> elements.
let idx = fromEnd ? a.length - n : n;
while ((fromEnd ? idx >= 1 : idx <= a.length))
{
a.splice(idx, 0, token);
idx = (fromEnd ? idx - n : idx + n + 1);
}
return a;
};
let array = Array.from("1234567890");
let res1 = insertTokenEveryN(array, ",", 3, true);
console.log(res1.join(""));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
但是,显然,就像人们评论的那样,您最好的选择是使用 input.toLocaleString('en-US')
:
let input = "1234567890";
console.log(Number(input).toLocaleString("en-US"));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
关于javascript - 在每个第 n 个位置插入到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54077062/