簡體   English   中英

在每第 n 個位置插入到數組中

[英]Insert into array at every nth position

我想要實現的是從一個簡單的字符串輸入創建一個帶有千位分隔符的格式化數字。 所以我的輸入看起來像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位置插入一個標記。 該解決方案使用帶有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;}

盡管在您的示例中您以字符串結尾,但標題顯示“放入數組”。 這是使用 lodash 的一種非常緊湊的方式:

import { chunk, flatten } from 'lodash'

const ADD_EVERY = 5
const ITEM_TO_ADD = {}

const data = flatten(
  chunk(input, ADD_EVERY).map((section) => 
  section.length === ADD_EVERY ? [...section, ITEM_TO_ADD] : section
)

它在概念上類似於執行 split().join()

您可以通過查找字符串末尾的一組三個字符來替換。

 var string = '12345678'; console.log(string.replace(/(?=(...)+$)/g, ','));

這是一個簡單的解決方案,但正則表達式更好。

 function separate(str, separator) { // Handling the head case (from 0 to 2 size) const headSize = str.length % 3; let newFormat = headSize ? `${str.substr(0, headSize)}${separator}` : ''; // Handle every 3 character const nbTripleChar = (str.length - headSize) / 3; for (let i = 0; i < nbTripleChar; i += 1) { newFormat = `${newFormat}${str.substr((i * 3) + headSize, 3)}`; if ((i + 1) !== nbTripleChar) { newFormat = `${newFormat}${separator}`; } } return newFormat; } console.log(separate('12515', ','));

您可以向后遍歷數組並使用第二個索引構建字符串。 字符串連接可能代價高昂,但它只迭代列表一次。 你也可以使用.reduce()在沒有 for 循環的情況下做到這一點(因為現在幾乎所有的數組迭代操作都可以作為函數調用來完成);

 let input = 123456789949949291; let array = input.toString().split(''); let candidateString = ''; for (let i = array.length-1; i >=0; i--) { candidateString=array[i]+candidateString; let revIndex=array.length-i; if(revIndex%3==0 && revIndex!== array.length){ candidateString = ','+candidateString; } } console.log(candidateString);

如果您不是 Regex 的粉絲。 或像 toLocaleString() 這樣的內置函數,這應該可以處理您可能遇到的大多數情況

 function format(str) { str = str.trim().replace(/\\s+/g, '') if (isNaN(str)) return 'NaN' str = str.split('') let strBuild = [str.pop()] for (let number of strBuild) { if (strBuild.length % 3 === 0) strBuild.unshift(str.pop() + ',') else strBuild.unshift(str.pop()) if (!str.length) return strBuild.join(''); } } console.log(format('1 ')) console.log(format('1 a 2')) console.log(format(' 12 ')) console.log(format('123 ')) console.log(format(' 123')) console.log(format(' 1 2 3')) console.log(format('1 2 3 ')) console.log(format('12 34')) console.log(format('123 45678')) console.log(format('12349 567 8')) console.log(format(' 1234 9567 81 ')) console.log(format(' 1234 9567 81 9 7 5 6 4 5 8 ')) console.log(format(' 1234 9567 81 c '))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM