Javascript charCodeAt()没有返回正确的代码..或者是吗?

时间:2014-09-12 03:23:41

标签: javascript

我试图找到密钥代码(如果这甚至是我需要的东西)并将字符更改为增加的密钥代码(这仅用于编码挑战)而且它不是工作

function LetterChanges(str) { 
var newString = "";
var keyCode;
  for(var i = 0; i < str.length; ++i)
  {

    keyCode = str.charCodeAt(i);
    console.log(keyCode);
    if( keyCode > 57 && keyCode < 122)
    {

         //add 1 to the keycode

         newString += String.fromCharCode(i+1);
         //console.log(String.fromCharCode(i+1));

    }
    else if(keyCode === 90)
    {
        //if it's a z being examined, add an a
         newString += "a";
    }
    else
        //it is a symbol, so just add it to the new string without change
        newString += str[i];
    }
  return newString.toUpperCase();

}

console.log(LetterChanges("Charlie"));

2 个答案:

答案 0 :(得分:2)

更改

newString += String.fromCharCode(i+1);

newString += String.fromCharCode(keyCode+1);

答案 1 :(得分:1)

Jsfiddle: http://jsfiddle.net/techsin/pnbuae83/1/

function codeIncreaser(input) {
    var str='', code=null;
    Array.prototype.forEach.call(input, function (e) {
        code = e.charCodeAt();
        if ((code>64 && code<90) || (code>96 && code<122)) {
            code++;
        } else if (code == 90) {
            code = 65;
        } else if (code == 122) {
            code = 97;
        }
        str += String.fromCharCode(code);
    });
    return str;
}

var text =  codeIncreaser('abczABC');
console.log(text);

这也适用于小写字母。

如果你想让代码变得有点紧凑,你可以做这样的事情......

function $(i) {
    var s='', c;
    Array.prototype.forEach.call(i, function (e) {
        c = e.charCodeAt();
        ((c>64&&c<90)||(c>96&&c<122))?c++:((c == 90)?c=65:(c==122&&(c=97)));
        s += String.fromCharCode(c);
    });
    return s;
}

console.log($('abczABC @-@'));