javascript - 在每个第 n 个位置插入到数组中

标签 javascript arrays

我想要实现的是从一个简单的字符串输入创建一个带有千位定界符的格式化数字。 所以我的输入看起来像 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/

相关文章:

javascript - 如何使用 Ramda 计算数组中的重复项?

javascript - 为什么在移动设备上单击涉及 jQuery ('#item' ).fadeOut() 调用的 <div>, '#item' css 保持其先前的悬停状态?

javascript - 有没有办法在 Sublime Text 中批量格式化代码?

javascript - 看似相等的物体其实并不相等

二维数组的 PHP 组合对作为 Christofides 算法解决方案的一部分

javascript - 日期数组排序/控制台错误?

javascript - 鼠标移开时关闭引导模式对话框

javascript - 计算 Sequelize.js 中联接表之间多对多表中的关系

arrays - 在 Swift 中从数组中选定的复选标记中删除字符串

python - 插入一个 numpy 数组以适应另一个数组