它正在停止,因为您已经通过 using 告诉它return newStr;
,它会立即终止函数并返回newStr
。
对于你正在做的事情,你想建立新的字符串,然后在最后返回它:
function uniCode(str, num) {
let newStr = "";
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i) + num;
let newChar = String.fromCharCode(charCode);
newStr += newChar;
}
return newStr;
}
现场示例:
function uniCode(str, num) {
let newStr = "";
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i) + num;
let newChar = String.fromCharCode(charCode);
newStr += newChar;
}
return newStr;
}
console.log(uniCode("Help!", 3)); // "Khos$"
但是请注意,当您遍历这样的字符串时,您正在使用代码单元,而不是代码点,如果存在需要多个代码单元来处理的代码点,这可能会使您的结果非常奇怪。(如果这些术语不熟悉,请参阅我的博客文章。)您可能想for-of
改用它,因为它适用于代码点:
function uniCode(str, num) {
let newStr = "";
for (const char of str) {
const codePointValue = char.codePointAt(0) + num;
const newChar = String.fromCodePoint(codePointValue);
newStr += newChar;
}
return newStr;
}
现场示例:
function uniCode(str, num) {
let newStr = "";
for (const char of str) {
const codePointValue = char.codePointAt(0) + num;
const newChar = String.fromCodePoint(codePointValue);
newStr += newChar;
}
return newStr;
}
function oldUniCode(str, num) {
let newStr = "";
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i) + num;
let newChar = String.fromCharCode(charCode);
newStr += newChar;
}
return newStr;
}
console.log("New: " + uniCode("Help!", 3)); // "New: Khos$"
console.log("Old: " + oldUniCode("Help!", 3)); // "Old: Khos$"