2

第一次提出问题——我是菜鸟——我找不到解决这个特定问题的方法。

目标是解码凯撒密码。我的代码可以将正确的字母代码放入数组中。我可以像这样手动将该数组转换为正确的字符串:

String.fromCharCode(89, 79, 85, 32, 68, 73, 68, 32, 73, 84, 33);

但是当我尝试将数组变成这样的字符串时:

  return String.fromCharCode(arr.join(", "));

它返回 \u0000 - 我收集的是 unicode 空字符。

任何人都可以解释发生了什么吗?

这是我的完整代码:

function rot13(str) {
  var arr = [];
  for (var i = 0; i < str.length; i++){
    if (str.charCodeAt(i) > 77 && str.charCodeAt(i) < 91){
      arr.push(str.charCodeAt(i) - 13);
    } else if (str.charCodeAt(i) <=77 && str.charCodeAt(i) > 64) {
      arr.push(str.charCodeAt(i) + 13);
    } else {
      arr.push(str.charCodeAt(i));
    }
  }
  console.log(arr);
  return String.fromCharCode(arr.join(", "));
}

rot13("LBH QVQ VG!");
String.fromCharCode(89, 79, 85, 32, 68, 73, 68, 32, 73, 84, 33);

4

1 回答 1

3

arr.join(',')不会扩展为函数的参数列表。您要么需要使用Function.apply ( .apply(null, arr)) ,要么如果您有 ES6 可用,请使用扩展运算符

return String.fromCharCode(...arr);

或者

return String.fromCharCode.apply(null, arr);

function rot13(str) {
  var arr = [];
  for (var i = 0; i < str.length; i++){
    if (str.charCodeAt(i) > 77 && str.charCodeAt(i) < 91){
      arr.push(str.charCodeAt(i) - 13);
    } else if (str.charCodeAt(i) <=77 && str.charCodeAt(i) > 64) {
      arr.push(str.charCodeAt(i) + 13);
    } else {
      arr.push(str.charCodeAt(i));
    }
  }

  return String.fromCharCode.apply(null, arr);
}

console.log(rot13("LBH QVQ VG!"));

于 2017-08-02T23:52:08.797 回答