我正在尝试解决此练习,其目标是给我一个必须转换为另一个字符串的字符串。新字符串的字符重复如下例所示。
例子:
累积(“abcd”);//"A-Bb-Ccc-Dddd"
我写了下面的代码:
function accum(s) {
counter = 0;
for (var i = 0; i < s.length; i++) {
return s[i].toUpperCase() + s[i].repeat(counter) + "-";
counter += 1;
}
}
当我尝试运行诸如 ZpglnRxqenU
之类的示例测试时,我收到此错误:
Expected: 'Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu', instead got: 'Z-'.
显然问题与不起作用的循环有关,但我不明白为什么。
最佳答案
这是一个 ES6 单行代码:
const accum = word => word.toLowerCase().split("").map( (letter,index) => letter.toUpperCase() + letter.repeat(index) ).join("-")
console.log( accum("ZpglnRxqenU") )
解释:
word.split("")
首先将您的字符串分解为字母数组.map( (letter,index) =>
遍历每个字母,边走边跟踪索引letter.toUpperCase() + letter.repeat(index)
用您返回的转换后的值替换每个字母- 此时,您有一组转换后的值
.join("-")
将所有内容连接回以“-”作为分隔符的字符串。
关于javascript - 遍历字符串并使用 repeat 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46891710/