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

การเปลี่ยนตัวพิมพ์เล็กเป็นใหญ่โดยไม่ใช้ toUpperCase() ใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่อยู่บนโพรโตไทป์ (prototype) ของคลาสสตริง ฟังก์ชันนี้ควรเปลี่ยนตัวอักษรทั้งหมดในสตริงเป็นตัวพิมพ์ใหญ่ (uppercase) และคืนค่าสตริงใหม่

ตัวอย่าง

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

const str = 'This is a lowercase String';
String.prototype.customToUpperCase = function(){
  const legend = 'abcdefghijklmnopqrstuvwxyz';
  const UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let res = '';
  for(let i = 0; i < this.length; i++){
    const el = this[i];
    const index = legend.indexOf(el);
    if(index !== -1){
      res += UPPER[index];
    }else{
      res += el;
    };
  };
  return res;
};
console.log(str.customToUpperCase());

ผลลัพธ์

ผลลัพธ์ในคอนโซล:

THIS IS A LOWERCASE STRING