在 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' ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP