2013-10-02 29 views
-1

如何在Javascript中增加一個字符串「A」來獲得「B」?如何在Javascript中增加一個字符的值

function incrementChar(c) 
{ 


} 
+1

要發生,如果什麼做你調用'incrementChar('Z')'? – Dai

+0

可能重複[什麼是可用於遞增字母的方法?](http://stackoverflow.com/questions/12504042/what-is-a-method-that-c​​an-be-used-to-increment -letters) – SomethingDark

回答

8

你可以嘗試

var yourChar = 'A' 
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B' 

所以,在一個函數:

function incrementChar(c) { 
    return String.fromCharCode(c.charCodeAt(0) + 1) 
} 

注意的是:這在ASCII order,例如'Z' -> '['。如果你想Z到回去A,嘗試一些稍微複雜一些:

var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('') 
function incrementChar(c) { 
    var index = alphabet.indexOf(c) 
    if (index == -1) return -1 // or whatever error value you want 
    return alphabet[index + 1 % alphabet.length] 
} 
+0

'index + i',我想你的意思是'index + 1'? – plalx

+0

@plalx呃,是的。這是一個錯字。固定 – Doorknob

1
var incrementString = function(string, count){ 
    var newString = []; 
    for(var i = 0; i < string.length; i++){ 
     newString[i] = String.fromCharCode(string[i].charCodeAt() + count); 
    } 
    newString = newString.join(''); 
    console.log(newString); 

    return newString; 
} 

此功能還可以幫助你,如果你有一個循環要經過