在 JavaScript 中將字串拆分為多個部分
需要編寫一個 JavaScript 函式,該函式接收一個字串和一個數字 n(n 整除字串的長度),並需要返回一個長度為 n 的字串陣列,該陣列包含該字串的 n 個相等部分。
示例
該程式碼如下所示 −
const str = 'we will be splitting this string into parts';
const num = 6;
const divideEqual = (str, num) => {
const len = str.length / num;
const creds = str.split("").reduce((acc, val) => {
let { res, currInd } = acc;
if(!res[currInd] || res[currInd].length < len){
res[currInd] = (res[currInd] || "") + val;
}else{
res[++currInd] = val;
};
return { res, currInd };
}, {
res: [],
currInd: 0
});
return creds.res;
};
console.log(divideEqual(str, num));輸出
控制檯中的輸出 −
[ 'we will ', 'be split', 'ting thi', 's string', ' into pa', 'rts' ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP