String.fromCharCode没有给出结果

String.fromCharCode gives no result javaScript

本文关键字:结果 fromCharCode String      更新时间:2023-09-26

运行代码后,我在窗口中没有得到结果。我找不到问题

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");

方法String.fromCharCode期望您将每个数字作为单独的参数传递。在您的代码示例中,您将数组作为单个参数传递,这将不起作用。

尝试使用apply()方法,这将允许你传递一个数组,它将转换成多个单独的参数:

var mystring = String.fromCharCode.apply(null, newte);

看起来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"));

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