gpt4 book ai didi

javascript - 字符串连接在 JS 范围内不起作用

转载 作者:行者123 更新时间:2023-12-03 02:30:52 25 4
gpt4 key购买 nike

无法使字符串连接工作

在下面的代码中,我无法将变量 temp 连接到变量 newString。我已经测试并发现这不是范围界定问题,但我仍然对这种行为感到困惑。

理解代码的目标

下面您可以看到一个代码示例,该示例采用带有 K(数字)和 S(字符串)的对象。该函数的目的是将字符在字母表中的位置移动数字 K,同时对于给定的字符串 S 保持其自身为大写或小写。

function shiftCharByInt(args){
const numb = args.K
const word = args.S
let newString = ''

for(let i=0;i<word.length;i++){
let character = word.charAt(i)
if(/^[a-z]+$/.test(character)){
let indexOfChar = character.charCodeAt(0)
indexOfChar+=numb
while(indexOfChar > 122) indexOfChar -= 26;
let temp = String.fromCharCode(indexOfChar)
newString.concat(temp)
continue;
}
if(/^[A-Z]+$/.test(character)){
let indexOfChar = character.charCodeAt(0)
indexOfChar+=numb
while(indexOfChar > 90) indexOfChar -= 26;
let temp = String.fromCharCode(indexOfChar)
newString.concat(temp)
continue;
}
newString += word
}
return newString
}

输入示例:

{
K: 11,
S: 'Hello - World'
}

示例输出:

"Spwwz - Hzcwo"

同样,我更感兴趣的是理解为什么 concat 不能优化代码本身。

最佳答案

您没有将值保存回 newString(concat 不会改变字符串值),请将其替换为

newString = newString.concat(temp);

newString = newString + word;//outside if

此外您无法为const重新分配值,因此请替换

const newString = ''

var newString = ''

演示

function test(args){
const numb = args.K
const word = args.S
var newString = ''

for(let i=0;i<word.length;i++){
debugger
let character = word.charAt(i)
if(/^[a-z]+$/.test(character)){
let indexOfChar = character.charCodeAt(0)
indexOfChar+=numb
while(indexOfChar > 122) indexOfChar -= 26;
let temp = String.fromCharCode(indexOfChar)
newString = newString.concat(temp)
continue;
}
if(/^[A-Z]+$/.test(character)){
let indexOfChar = character.charCodeAt(0)
indexOfChar+=numb
while(indexOfChar > 90) indexOfChar -= 26;
let temp = String.fromCharCode(indexOfChar)
newString = newString.concat(temp)
continue;
}
newString = newString + character;
}
return newString
}

console.log(test({
K: 11,
S: 'Hello - World'
}));

关于javascript - 字符串连接在 JS 范围内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48744357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com