将字符串分成n个相等的部分-JavaScript
我们需要编写一个JavaScript函数,该函数接受一个字符串和一个数字n(以使n精确地划分字符串的长度)。我们需要返回一个长度为n的字符串数组,其中包含n个相等的部分。
让我们为该函数编写代码-
示例
const str = 'this is a sample string';
const num = 5;
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));输出结果
以下是控制台中的输出-
[ 'this ', 'is a ', 'sampl', 'e str', 'ing' ]
热门推荐
10 拜年祝福语 简短句子
11 小姨生日祝福语简短独特
12 国庆中秋祝福语简短搞笑
13 高考送考祝福语简短
14 生日祝福语大全女生简短
15 怎么生孩子祝福语简短
16 祖国七十华诞简短祝福语
17 舅妈生日红包祝福语简短
18 奶奶八十寿辰祝福语简短