字符串Concat在范围JS中不起作用 [英] String Concat not working in scope JS
问题描述
在下面的代码中,我无法将变量 temp
连接到变量 newString
.我进行了测试,发现这不是范围界定的问题,但是我仍然对此行为感到困惑.
In the code below I am not able to concat the variable temp
to the variable newString
. I have tested and seen that this is not an issue of scoping but I am still puzzled by this behavior.
了解代码的目标
在下面,您将看到一个代码示例,该代码采用带有K(一个数字)和S(一个字符串)的对象.该功能旨在将字符在字母中的位置移位数字K,同时对于给定的String S,将其自身保持为大写或小写.
Below you can see an example of the code which takes an object with K (a number) and S (a string). The function is meant to shift the character's position in the alphabet by the number K while keeping itself as Upper or Lowercase for a given String 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无法优化代码本身更感兴趣.
Again, I am more interested in understanding why concat does not work optimising the code itself.
推荐答案
您没有将值保存回 newString
( concat
不会对字符串值),将其替换为
You are not saving the value back to newString
(concat
doesn't mutate the string value), replace it by
newString = newString.concat(temp);
和
newString = newString + word;//outside if
您也不能将值重新分配给 const
,因此请替换
Also you can't re-assign a value to const
, so replace
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'
}));
这篇关于字符串Concat在范围JS中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!