String Concat在范围JS中不起作用

时间:2018-02-12 10:34:53

标签: javascript concatenation string-concatenation

无法使String Concat工作

在下面的代码中,我无法将变量$num1 = 10; // $num1 = 10, no issue while ($num1 < 20) { // If $num1 is less than 20, do // everything between { and } $num1++; // Increment the value of $num1 by 1 echo $num1; // print the value of $num1 as it is // at this point of time. // This will be in the range from // 11 (not 10) to 20 } // And finally for testing echo $num1; // displays 20 as that is current value // of $num1 连接到变量temp。我已经测试并发现这不是范围问题,但我仍然对这种行为感到困惑。

了解代码的目标

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

newString

示例输入:

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'
}

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

1 个答案:

答案 0 :(得分:0)

您尚未将值保存回newStringconcat 不会改变字符串值),请将其替换为

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'
}));