如何将javascript中的字母增加到下一个字母?

Rol*_*ndo 2 javascript

我想要一个可以从 A 到 B、B 到 C、Z 到 A 的函数。

我的功能目前是这样的:

function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
Run Code Online (Sandbox Code Playgroud)

它适用于 A 到 X,但是当我使用 Z 时......它转到 [ 而不是 A。

kin*_*ser 5

条件简单。

function nextChar(c) {
    var res = c == 'z' ? 'a' : c == 'Z' ? 'A' : String.fromCharCode(c.charCodeAt(0) + 1);
    console.log(res);
}
nextChar('Z');
nextChar('z');
nextChar('a');
Run Code Online (Sandbox Code Playgroud)


Nin*_*olz 5

可以使用parseIntradix36和相反的方法Number#toString具有相同的基数,并且该值的校正。

function nextChar(c) {
    var i = (parseInt(c, 36) + 1 ) % 36;
    return (!i * 10 + i).toString(36);
}

console.log(nextChar('a'));
console.log(nextChar('z'));
Run Code Online (Sandbox Code Playgroud)