所以我有一個串列var be = ["Hello", "welcome", "Hi", "morning", "Hi"],如果最終字串不超過 12,我想加入字串。
所以最終結果必須是一個串列: ["Hello--welcome", "Hi--morning--Hi"] // I need the -- included
我嘗試通過將它們加入一個大字串然后使用 .match 來使用正則運算式,但沒有奏效。
編輯:
這是我試過的:
var s = ["Hello", "welcome", "Hi", "morning", "Hi"].join("--")
var result = s.match(/.{1,12}/g) // ['Hello--welco', 'me--Hi--morn', 'ing--Hi']
謝謝
uj5u.com熱心網友回復:
- 使用
Array#reduce, 迭代陣列,同時使用words陣列和total(單詞的總長度)更新物件串列。在每次迭代時,檢查將當前字串添加到最后添加的物件是否會超過“MAX_LENGTH”,如果不更新它,否則添加一個新物件 - 使用
Array#mapandArray#join,回傳連接的單詞串列
const
arr = ["Hello", "welcome", "Hi", "morning", "Hi"],
MAX_LENGTH = 12;
const res =
arr.reduce((list, str) => {
const last = list[list.length-1];
if(last && last.total str.length <= MAX_LENGTH) {
last.total = str.length;
last.words.push(str);
} else {
list.push({ total: str.length, words: [str] });
}
return list;
}, [])
.map(({ words }) => words.join('--'));
console.log(res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361531.html
標籤:javascript 数组
下一篇:如何回傳具有給定值的物件?
