在 JavaScript 中更改大小寫,不使用 String.prototype.toUpperCase()


問題

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

此函式應簡單地將字串中所有存在的字母的字母大小寫更改為大寫並返回新字串。

示例

以下是程式碼 −

 線上示例

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

更新時間: 17-4-2021

529 次瀏覽

職業生涯起航

完成課程獲得認證

開始
廣告
© . All rights reserved.