toUpperCase和toLowerCase的实现

实现过程(以小写转大写为例):

  • 将字符串拆开为一个一个字符
  • 使用charCodeAt获取每个字符的ASCII码
  • 使用String.fromCharCodeASCII码-32的结果转化为字符
  • 合并转换后的数组
function toUpperCase(str) {
    let arr = str.split('');
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] >= 'a' && arr[i] <= 'z') {
            // 获取ASCII码再-32
            let code = arr[i].charCodeAt();
            arr[i] = String.fromCharCode(code - 32);
        }
    }
    return arr.join('');
}

let test1 = toUpperCase('wdsxzxfd8');
console.log(test1);//WDSXZXFD8


function toLowerCase(str) {
    let arr = str.split('');
    for (let i = 0; i < str.length; i++) {
        if (arr[i] >= 'A' && arr[i] <= 'Z') {
            let code = arr[i].charCodeAt();
            arr[i] = String.fromCharCode(code + 32);
        }
    }
    return arr.join('');
}
let test2 = toLowerCase('ASCSC576TV');
console.log(test2);//ascsc576tv
原文地址:https://www.cnblogs.com/aeipyuan/p/12990172.html