在 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP