堆纸机,请帮助我疲惫的初学者的大脑,并让我知道我的位置。
我的函数接受小写字符串作为唯一参数。可以返回相同的字符串,并且每个单词均使用大写的偶数索引字符。但是实际输出与我的预期输出不同。
例如:
console.log(toWeirdCase('harry enjoys reading books'))
//expected output: 'HaRrY EnJoYs ReAdInG BoOkS'
// actual output: 'HaRrY EnJoYs ReAdInG BookS'
console.log(toWeirdCase('gooooooogle search in vain'));
//expected output: 'GoOoOoOoGlE SeArCh In VaIn'
// actual output: GoooooooGlE SeArCh In VaIn
function toWeirdCase(string) {
string = string.split(" ");
for (let i = 0; i < string.length; i++) {
for (let x = 0; x < string[i].length; x++) {
if (string[i].indexOf(string[i].charAt(x)) % 2 == 0) {
string[i] = string[i].replace(string[i].charAt(x), string[i].charAt(x).toUpperCase());
}
}
}
return string.join(" ");
}
最佳答案
当您使用indexOf
查找字符时,将获得第一次出现的索引,而不一定是最初查看的索引。同样,replace
(当给定字符串值作为第一个参数时)将替换第一个匹配项,不一定替换您感兴趣的匹配项。
这是一个修复程序,而没有太多改变您的原始版本:
function toWeirdCase(string){
string = string.split(" ");
for (let i = 0; i<string.length; i++) {
for (let x = 0; x < string[i].length; x++) {
if (x % 2 == 0) {
// Only modify the single character of interest. The rest is sliced in
string[i] = string[i].slice(0, x) + string[i][x].toUpperCase() + string[i].slice(x+1);
}
}
}
return string.join(" ");
}
console.log(toWeirdCase('harry enjoys reading books'))
console.log(toWeirdCase('gooooooogle search in vain'));
另类
您也可以采用不同的方法,而不是将字符串拆分为单词,而只是在看到空格时重置标志。
在这里,您可以看到使用
reduce
实现的想法,从而产生了功能强大的编程风格解决方案:function toWeirdCase(string){
return [...string].reduce(
([str, j], c, i) => c === " " || j ? [str + c, 0] : [str + c.toUpperCase(), 1],
["", 0]
)[0];
}
console.log(toWeirdCase('harry enjoys reading books'))
console.log(toWeirdCase('gooooooogle search in vain'));
关于javascript - Javascript-字符串大写函数引发奇怪的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53468121/