如何在Javascript中增加字符的值
如何在Javascript中增加字符串a以获得B如何在Javascript中增加字符的值,javascript,Javascript,如何在Javascript中增加字符串a以获得B function incrementChar(c) { } 你可以试试 var yourChar = 'A' var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B' 因此,在函数中: function incrementChar(c) { return String.fromCharCode(c.charCodeAt(0) + 1) } 请注意,这
function incrementChar(c)
{
}
你可以试试
var yourChar = 'A'
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B'
因此,在函数中:
function incrementChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1)
}
请注意,这会出现在中,例如“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]
}
如果你有一个循环要执行,这个函数也可以帮助你如果你调用incrementChar'Z',你希望发生什么?索引+i的可能重复,我猜你是指索引+1?@plalx哇,是的。这是一个打字错误。修复了
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;
}