将字符串分成 n 个相等的部分 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/11/24 22:04:17

我们需要编写一个 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' ]

相关文章


有用资源