Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การสร้างฟังก์ชัน customSplit คล้าย String.prototype.split() ใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่อยู่บนโพรโตไทป์ของคลาส String ควรรับตัวคั่น (separator) เป็นอาร์กิวเมนต์เดียว (split จริงรับ 2 อาร์กิวเมนต์) และคืนค่าอาร์เรย์ของส่วนต่างๆ ของสตริงที่ถูกแยกโดยตัวคั่น

ตัวอย่าง

โค้ดตัวอย่างดังนี้:

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' ]