將字串拆分為相等部分 JavaScript


我們需要編寫一個 JavaScript 函式,它接收一個字串和一個數字 n 作為兩個引數(該數字應恰好可以整除字串的長度)。並且我們必須返回一個包含 n 個長度相等的字串的陣列。

例如,−

If the string is "helloo" and the number is 3
Our output should be:
["ho", "eo", "ll"]

此處,每個子字串都準確包含(陣列長度/n)個字元。並且每個子字串透過交替獲取字串中相應的第一個和最後一個字母來形成

讓我們編寫此函式的程式碼 −

示例

const str = 'helloo';
const splitEqual = (str, n) => {
   if(str.length % n !== 0){
      return false;
   }
   const len = str.length / n;
   const strArray = str.split("");
   const arr = [];
   let i = 0, char;
   while(strArray.length){
      if(i % 2 === 0){
         char = strArray.shift();
      }else{
         char = strArray.pop();
      };
      if(i % len === 0){
         arr[i / len] = char;
      }else{
         arr[Math.floor(i / len)] += char;
      };
      i++;
   };
   return arr;
};
console.log(splitEqual(str, 3));

輸出

控制檯中的輸出將為 −

[ 'ho', 'eo', 'll' ]

更新時間:2020 年 8 月 31 日

801 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告