在 JavaScript 中實現自定義函式,如 String.prototype.split() 函式


問題

我們需要編寫一個JavaScript函式,該函式存在於 String 類的原型物件上。

它應該只接受一個字串分隔符作為唯一引數(儘管原始 split 函式接受兩個引數)。而我們的函式應該返回一個由分隔符分隔和拆分的字串部分的陣列。

示例

下面的程式碼是 -

 動態展示

const str = 'this is some string';
String.prototype.customSplit = (sep = '') => {
   const res = [];
   let temp = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(el === sep || sep === '' && temp){
         res.push(temp);
         temp = '';
      };
      if(el !== sep){
         temp += el;
      }
   };
   if(temp){
      res.push(temp);
      temp = '';
   };
   return res;
};
console.log(str.customSplit(' '));

輸出

[ 'this', 'is', 'some', 'string' ]

更新於: 17-4-2021

993 次瀏覽

開啟你的事業

透過完成課程獲取認證

開始學習
廣告
© . All rights reserved.