更改字母算法,适用于 JSBIN 但不适用于 Coderbyte,寻求澄清 [英] Changing Letters Algorithm, works in JSBIN but not in Coderbyte, seeking clarification

查看:24
本文介绍了更改字母算法,适用于 JSBIN 但不适用于 Coderbyte,寻求澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在完成 CoderByte 练习,但遇到了以下问题:

I'm going through the CoderByte exercises and I came across the following problem:

>使用 JavaScript 语言,让函数 LetterChanges(str) 获取传递的 str 参数并使用以下算法对其进行修改.用字母表中紧随其后的字母替换字符串中的每个字母(即,c 变为 d,z 变为 a).然后将这个新字符串中的每个元音字母 (a, e, i, o, u) 大写,最后返回这个修改后的字符串.

我在 JSBin 中写出它并且它工作正常(即使是 te,但在 CoderByte 中它没有.我想问社区我写的是否正确并且这是 CoderByte 上的问题,或者我的代码是否正确错误,问题出在 JSBin 上.

I wrote out it out in JSBin and it worked fine (even te, but in CoderByte it didn't. I want to ask the community if what I wrote is correct and it's an issue on CoderByte, or if my code is wrong and the issue is with JSBin.

代码如下:

function LetterChanges(str) {
    var iLetters = str.split('');
    var newStr = [];

    for (var i = 0; i < str.length; i++) {
        if (/[a-y]/ig.test(iLetters[i])) {
            newStr[i] = String.fromCharCode(iLetters[i].charCodeAt(0) + 1);
            if (/[aeiou]/ig.test(newStr[i])) {
                newStr[i] = newStr[i].toUpperCase();
            }
        } else if (/[z]/ig.test(iLetters[i])) {
            newStr[i] = "A";
        } else if (/[^A-Z]/ig.test(iLetters[i])) {
            newStr[i] = iLetters[i];
        }
    }

    return newStr.join('');
}

推荐答案

看起来确实像是他们后端 JS 运行器上的一个错误.正如您所说,您的代码运行良好,应该被接受.值得向他们的支持 imo 报告.

Seems like a bug on their back-end JS runner indeed. As you've stated, your code runs fine and should be accepted. Worth reporting it to their support imo.

这是一个替代解决方案 指定一个作为.replace()的第二个参数的函数:

Here's an alternative solution specifying a function as second parameter to .replace():

function LetterChanges(str) {
  return str.replace(/[a-z]/ig, function(c) {
    return c.toUpperCase() === 'Z' ? 'A' : String.fromCharCode(c.charCodeAt(0) + 1);
  }).replace(/[aeiou]/g, function(c) {
    return c.toUpperCase();
  });
}

这篇关于更改字母算法,适用于 JSBIN 但不适用于 Coderbyte,寻求澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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