我在 JavaScript 中的 rot13 实现哪里出错了? [英] Where is my implementation of rot13 in JavaScript going wrong?

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

问题描述

有问题的代码在这里高亮显示:来自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 对象的原型,我有一个我之前设置的 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 实现哪里出错了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆