如果空格不能与 charAt 一起正常工作

问题描述 投票:0回答:1

在这段代码中,我从网站 codeHs 中获取了一个随机字符串,我必须这样做 要做的是创建一个程序来返回这样的随机字符串,如果

str
= hello
,这将是输出
-->
Hello
然后
hEllo
然后
heLlo
然后
helLo
然后
hellO
,它也应该跳过空格并直接转到下一个变量

我当前的代码是

function wave(str){
  var str2 = [];
  var j = 0;
  for (var i = 0; i < str.length; i++, j++)
    {
      if (!/^\s*$/.test(str.charAt(i)))
        {
          str2[j] =  str.slice(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1)
        }
      else if (i + 1 < str.length)
        {
          i += 1;
          str2[j] =  str.slice(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1)
        }
    }
  console.log(str2)
  console.log(str.length)
  return str2;
  
}

当我在测试模式下运行它时,它给了我

this is the image

当我在尝试模式下运行它时,它给了我

this is the image

基本测试没问题,但不适用于随机测试,这是错误,我不知道如何修复它,看起来是 if 语句未正确触发的错误

enter image description here

javascript string if-statement whitespace charat
1个回答
0
投票

您面临的问题是当连续有两个空格时。你的问题是,在你的

else
块中,你假设如果遇到空格,那么下一个字符将不是空格,并将其推入
str2
(导致单词不包含大写字母,因为您刚刚通过尝试大写空格来推送新项目)。

相反,请完全移除

else
块。不需要它,因为一旦您最终在循环中到达下一个非空格字符,您将处理下一个非空格字符,不要尝试提前处理下一个字符,因为当您到达它时,循环会为您执行此操作。请注意,现在只需在将转换后的单词添加到数组时增加
j
,而不是每次迭代时都需要增加

function wave(str) {
  var str2 = [];
  var j = 0;
  for (var i = 0; i < str.length; i++) {
    if (!/^\s*$/.test(str.charAt(i))) {
      str2[j] = str.slice(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1);
      j++;
    }
  }
  return str2;
}

console.log(wave("hello"));
console.log(wave("abc  efg"));

可以使用

j
:
 简化上述代码以删除正则表达式检查和 
.push()

计数器

function wave(str) {
  var result = [];
  for (var i = 0; i < str.length; i++) {
    if (str.charAt(i) != " ") { // or just str[i] != " "
      result.push(str.slice(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1));
    }
  }
  return result;
}

console.log(wave("abc  efg"));

© www.soinside.com 2019 - 2024. All rights reserved.