在 JavaScript 中将字符串拆分成几部分
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/25 7:08:17
我们需要编写一个 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' ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

