【问题标题】:how to increment the value of a char in Javascript如何在Javascript中增加char的值
【发布时间】:2013-10-08 08:22:49
【问题描述】:

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

function incrementChar(c)
{


}

【问题讨论】:

标签: javascript


【解决方案1】:

你可以试试

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]
}

【讨论】:

  • index + i,我猜你的意思是index + 1?
  • @plalx 哎呀,是的。那是一个错字。固定
【解决方案2】:
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;
}

如果你有一个循环要通过,这个函数也可以帮助你

【讨论】:

    猜你喜欢
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多