本文介绍了JavaScript中rot13的实现在哪里出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有问题的代码,其语法在此处突出显示:

Code in question with syntax highlighting here: via Friendpaste

rot13.js:

<script>
String.prototype.rot13 = rot13 = function(s)
 {
    return (s = (s) ? s : this).split('').map(function(_)
     {
        if (!_.match(/[A-Za-z]/)) return _;
        c = Math.floor(_.charCodeAt(0) / 97);
        k = (_.toLowerCase().charCodeAt(0) - 96) % 26 + 13;
        return String.fromCharCode(k + ((c == 0) ? 64 : 96));
     }).join('');
 };
</script>


如您所见,实际上只用一行附加作为String对象的原型方法,我有一个之前设置的map()方法(我确定该代码可以正常工作;它只是遍历数组中的每个元素并应用在其中指定的函数参数)遍历字符串中的每个字符,然后执行我认为是将字符串转换为rot13'对应字符的正确计算。可悲的是我被误解了。有人可以发现我出了错吗?

As you can see, using quite literally a single line to attach a method to the String object a la prototyping, I'm having a map() method that I previously set up (I know for sure that that code works perfectly; it's simply iterating over each element in the array and applying the function specified in the parameter) go over each character in a string and do what I thought were the proper calculations to transform the string into it's rot13'd counterpart. I was sadly mistaken. Can anybody spot where I went wrong?

推荐答案

您可以使用超短代码:

s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});

这篇关于JavaScript中rot13的实现在哪里出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 03:45