I have a function that removes vowels from a string, and then returns the string. My problem is that where there's two or more consecutive vowels it will only remove one of them. I can run the 'for' loop twice to fix the issues, but that doesn't seem right. Is there anything I could change?

let string = "I'd always thought lightning was something only I could see.";
let vowels = ['a', 'e', 'i', 'o', 'u']

function removeVowels(str) {
  let stringArray = str.split('');
  for (let letter of stringArray){
    if (vowels.includes(letter.toLowerCase())){
      let index = stringArray.indexOf(letter); 
      stringArray.splice(index, 1);
    }
  }
  return stringArray.join('');
}

Returns:

"'d lwys thught lghtnng ws smthng nly  culd se."

推荐答案

When iterating forward, the splice shifts the next element of the array backward, under the iterating index; then incrementing the index misses that element.

It's fixable in a few ways, but doing the least damage to your approach, just iterate the letters in reverse so the iteration and deletion don't interfere with one another...

let string = "I'd always thought lightning was something only I could see.";
let vowels = ['a', 'e', 'i', 'o', 'u'];

function removeVowels(str) {
  let stringArray = str.split('');
  for (let i=stringArray.length-1; i>=0; i--){
    let letter = stringArray[i];
    if (vowels.includes(letter.toLowerCase())){
      stringArray.splice(i, 1);
    }
  }
  return stringArray.join('');
}

console.log(removeVowels(string))

Since we're iterating over the indexes, a side benefit is that we don't have to search the array with indexOf().

Javascript相关问答推荐

悬停时暂时偏离 CSS 动画,然后恢复

无法在两个 Python aiortc 脚本之间完全建立 ICE 连接

如何等待 observable 完成返回值?

使用多个 Select 选项过滤数组

如何从流中获取数据?

如果 textarea 为空,如何使按钮禁用

如何在 React 中对数组的每个元素进行切片

Bootstrap 按钮插件似乎没有应用按钮插件

Rails 7 JavaScript 事件监听器在浏览器返回后停止工作?

如何在同一个对象键下存储不同类型的函数?

如何在 VUE 中插入换行符,为文本呈现 html?

如何在 Vue.js 上为卡片组件添加缺口

我想阻止用户在他们使用正则表达式(regexp)输入 0 时输入

jquery/javascript 输入复选框选中属性(只读不工作)

为什么这个函数会改变数组项的顺序?

为什么 javascript 渲染已移除的组件

即使不满足 while 循环的条件,仍会调用递归函数

对多个值的数据属性停止计数器

掷骰子. DND,将数组中的数字相加

如何屏幕录制滚动的 n 秒窗口