凡在JavaScript中我单行执行ROT13的问题呢? [英] Where is my one-line implementation of rot13 in JavaScript going wrong?
问题描述
code问题语法高亮这里:通过Friendpaste
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对象一拉成型,我有一张地图()方法,我previously成立了(我知道肯定是code完美的作品,它只是遍历数组中的每个元素和应用参数中指定的函数)去了每一个字符的字符串,做我认为是正确的计算转换串入它的rot13'd对口。我是大错特错了。任何人都可以发现我哪里错了?
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的问题呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!