ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน 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' ]