2016-10-20 51 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