將字串分成 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' ]

更新於: 14-Sep-2020

541 人瀏覽

開啟你的 職業生涯

完成本課程後獲得認證

入門
廣告