【问题标题】:Splice in function doesn't change a character as expected函数中的拼接不会按预期更改字符
【发布时间】:2020-05-07 15:59:00
【问题描述】:

我已经在这个函数上工作了一段时间,但我无法弄清楚为什么即使我使用 .splice() 我也没有得到修改后的数组。 我提供了开始更改数组“i”的索引、要删除的元素数量“1”和要添加的元素“str[i]”。

function wave(str) {
  let result = [];
  for (let i = 0; i < str.length; i++) {
    if ((/[a-z]/ig).test(str[i])) {
      let st = str.split("").splice(i, 1 , str[i].toUpperCase());
      result.push(st);
    }
  }
 return result;

}


console.log(wave('hello')); // expected ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
console.log(wave("two words")); // ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];

【问题讨论】:

  • 你可能想加入分割字符串,否则它将保持一个数组。
  • There's 有点faster 和用高阶方法实现目标的更短的方法,以防万一......

标签: javascript for-loop splice array-splice


【解决方案1】:

Array#splice 返回删除的项目。您需要保留数组 - 并删除和添加新项目。

访问RegExp#test方法的正则表达式不需要用括号括起来。

在推送到数组之前,您需要使用Array#join 来获取单个字符串。

function wave(str) {
    let result = [];
    for (let i = 0; i < str.length; i++) {
        if (/[a-z]/ig.test(str[i])) {
            let st = str.split("");
            st.splice(i, 1, str[i].toUpperCase());
            result.push(st.join(''));
        }
    }
    return result;
}

console.log(wave('hello')); // expected ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
console.log(wave("two words")); // ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 感谢您的帮助。我无法弄清楚为什么只返回删除的字符的原因。并指出我不需要为正则表达式包装我的表达式。我刚开始使用它们,所以我还不太自信。
  • @Mugg84 : '...为什么只删除' 这就是 splice() 方法的工作方式 - 它编辑数组并仅返回删除的部分(阅读通过文档进行综合参考); '...don't need to wrap' - 这里根本不需要正则表达式,而且它会降低你的代码性能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 2018-11-09
  • 2023-02-24
  • 1970-01-01
相关资源
最近更新 更多