如何在Javascript中增加char的值

use*_*724 0 javascript

如何在Javascript中增加字符串"A"以获得"B"?

function incrementChar(c)
{


}
Run Code Online (Sandbox Code Playgroud)

Doo*_*nob 9

你可以试试

var yourChar = 'A'
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B'
Run Code Online (Sandbox Code Playgroud)

所以,在一个函数中:

function incrementChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1)
}
Run Code Online (Sandbox Code Playgroud)

请注意,例如,这将按ASCII顺序排列'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]
}
Run Code Online (Sandbox Code Playgroud)