2016-10-20 53 views
-1

我在窗口中没有得到结果。我不能找到问题 结果必须从charCode创建字符串。String.fromCharCode在运行代码后没有得到结果javaScript

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

+1

你对返回的值什么都不做 - 你期望什么? – Li357

+1

'String.fromCharCode(newte);'可能不会做你期望的任何一个 –

+0

你能解释我的想法吗?我尝试了''几种不同的情况,我总是得到错误或没有任何东西 – EdenLT

回答

0

String.fromCharCode期望用户通过每个数作为一个单独的参数的方法。在你的代码示例中,你传递一个数组作为单个参数,这是行不通的。

尝试使用apply()方法来代替,这将允许你通过一个数组,它会转换到这多个单独的参数:

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

'.call'不以这种方式获取数组,这就是'.apply'。 –

+0

哎呀,是的,你是完全正确的。更新答案。 –

+0

很好的解释史蒂文谢谢你。 – EdenLT

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

注:我复制你的逻辑的字符替换,但it doesn't seem correct

+0

是啊,我发现我没有得到结果,因为我的预期:)去工作更多。 – EdenLT