javascript - 如何在不使用 JavaScript 中的内置函数的情况下将字符串大写转换为小写
问题描述
如何在不使用 JavaScript 中的内置函数的情况下将字符串大写转换为小写。
在不使用 JavaScript 中的任何内置方法的情况下将大写转换为小写。我有一个解决方案
var testCase = 'HELLO WORLD';
var length = 0;
var finalAnswer = '';
var answer = [];
while (testCase[length] !==
undefined) {
length++;
}
for (var i = 0; i < length; i++) {
answer.push(testCase[i]);
}
for (var i = 0; i < length; i++) {
if (testCase[i] == 'A')
answer[i] = 'a';
else if (testCase[i] == 'B')
answer[i] = 'b'
else if (testCase[i] == 'C')
answer[i] = 'c'
else if (testCase[i] == 'D')
answer[i] = 'd'
.
.
.
else if (testCase[i] == 'Y')
answer[i] = 'y'
else if (testCase[i] == 'Z')
answer[i] = 'z'
}
for (var i = 0; i < length; i++) {
finalAnswer = finalAnswer + answer[i];
}
console.log(finalAnswer)
给一些更好的解决方案。
解决方案
您可以使用String.fromCharCode
andcharCodeAt
转换 from uppercase
tolowercase
而不使用任何方法
one-liner solution
const result = testCase
.split("")
.map((c) =>
c.charCodeAt() >= 65 && c.charCodeAt() <= 90
? String.fromCharCode(c.charCodeAt() + 32)
: c
)
.join("");
var testCase = "HELLO WORLD";
const result = [];
for (let c of testCase) {
if (c.charCodeAt() >= 65 && c.charCodeAt() <= 90)
result.push(String.fromCharCode(c.charCodeAt() + 32));
else result.push(c);
}
console.log(result.join(""));