2017-08-02 29 views
2

第一次問一個問題 - 我是一個noob - 我找不到這個問題。爲什麼我在使用String.fromCharCode時不能使用字符而是 u0000?

目標是解碼凱撒密碼。我的代碼工作到將正確的字母代碼放入數組中。 我可以手動開啓該數組到正確的字符串是這樣的:

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

+1

'使用String.fromCharCode(改編。 join(「,」));'沒有任何意義。 – Pointy

+0

嘗試從你的String.fromCharCode(arr.join(「,」))中取出你的「arr.join」,因爲'String.fromCharCode()'將把字符列表變成一個字符串。 –

+0

'String.fromCharCode'會將它的參數'89,79,85,32,68,73,68,32,73,84,33「'轉換爲一個數字,該數字給出'NaN',它被視爲等效的到'0'。 – Bergi

回答

3

arr.join(',')不會擴大到參數的函數列表。你要麼需要使用Function.apply.apply(null, arr)),或者如果你有ES6可用,使用spread operator

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

相關問題