-1

运行代码后,我在窗口中没有得到任何结果。我找不到问题结果必须是从 charCode 创建的字符串。

function rot13(str) {
  var te = [];
  var i = 0;
  var a = 0;
  var newte = [];

  while (i < str.length) {
    te[i] = str.charCodeAt(i);
    i++;
  }
  while (a != te.length) {
    if (te[a] < 65) {
      newte[a] = te[a] + 13;
    } else
      newte[a] = te[a];
    a++;
  }

  var mystring = String.fromCharCode(newte);


  return mystring;
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

4

2 回答 2

0

该方法String.fromCharCode希望您将每个数字作为单独的参数传递。在您的代码示例中,您将数组作为单个参数传递,这是行不通的。

尝试改用该apply()方法,这将允许您传递一个数组,并将其转换为多个单独的参数:

var mystring = String.fromCharCode.apply(null, newte);
于 2016-10-20T01:11:01.323 回答
0

看起来String.fromCharCode()没有定义为对数组进行操作。

试试这样:

function rot13(str) {
  var result = "";
  
  for (var i = 0; i < str.length; i++) {
    var charCode = str.charCodeAt(i) + 1;
    
    if (charCode < 65) {
      charCode += 13;
    }
    
    result += String.fromCharCode(charCode);
  }
  
  return result;
}

// Change the inputs below to test
console.log(rot13("SERR PBQR PNZC"));

注意:我复制了您的字符替换逻辑,但它似乎不正确

于 2016-10-20T01:13:18.123 回答