为什么此功能不能删除元音?

时间:2018-10-23 19:53:25

标签: javascript

我创建了一个函数,该函数使用字符串将字符串转换为数组,然后将每个字符串字符与数组中的每个元音进行比较,如果该字符串字符与之匹配则将其删除。在更长的单词上似乎无法正常工作。例如,使用“ tom”将删除o,但使用“ johnson”将仅删除第一个o,然后在末尾也删除n。我没看到问题。

function removeVolwels(string){

  let strAr= function(string){
     //converts to to lower case and turns string into an array
      let s= string.toLowerCase();
      let strAr= s.split("");
      return strAr;
  }(string);
   //stores vowels
  let vowels=["a","e","o","i","u","y"];

  //loops through each character
  for(let i=0; i < string.length -1; i++){
      console.log("i index " + i);
  //compares each  character in the string to a every vowel until it matches one
      for(let j=0; j < vowels.length; j++){
          console.log("j index " + j + " and " +vowels[j]);
         if(string[i] === vowels[j]){
              console.log(string[i].toString() + " === "+vowels[j]);
             console.log("removed " + string[i]);
            //removes vowel if letter matches one
             strAr.splice(i,1);
             console.log(strAr)
         } 
      }
  }
  
  return strAr.join("");
}

console.log('tom => ' + removeVolwels('tom'));
console.log('johnson => ' + removeVolwels('johnson'));

4 个答案:

答案 0 :(得分:3)

问题是您打电话给strAr.splice(i,1);

因此,您有单词“ johnson”,并且在删除第一个“ o”之后得到了“ jhnson”,但是当前字符串的长度是6而不是开头的7!

当您到达下一个“ o”时-i的值为5(对于“ johnson”字符串正确,但对“ jhnson”不是正确的)。

此外,循环中还有另一个错误-您的条件为i < string.length -1。这意味着您将永远无法达到最后一个角色。应该是i < string.length

因此,如果您想重用解决方案,则可以编写如下内容:

function removeVolwels(string){

  let strAr= function(string){
     //converts to to lower case and turns string into an array
      let s= string.toLowerCase();
      let strAr= s.split("");
      return strAr;
  }(string);
   //stores vowels
  let vowels=["a","e","o","i","u","y"];
  let returnVal = [];
  //loops through each character
  for(let i=0; i < string.length; i++){
      console.log("i index " + i);
      // simple flag to match if letter should be added to return array
      let shouldBeAdded = true;
      //compares each  character in the string to a every vowel until it matches one
      for(let j=0; j < vowels.length; j++){
          console.log("j index " + j + " and " +vowels[j]);
          if(string[i] === vowels[j]){
              // when it is some of the vowels it should not be added, so we change the flag, and break 'vowel loop'
              shouldBeAdded = false;
              break;
          } 
      }
      // if flag is true then add letter to result array
      if(shouldBeAdded === true) {
          returnVal.push(string[i])
      }
  }
  
  return returnVal.join("");
}

console.log('tom => ' + removeVolwels('tom'));
console.log('johnson => ' + removeVolwels('johnson'));

答案 1 :(得分:2)

您似乎使事情变得有些复杂。下面是一种简化的工作方式(代码已注释)。

function removeVowels(string) {
  // convert string to lowercase and split into array 's'
  let s = string.toLowerCase().split("");

  // define our list of vowels
  let vowels = ["a", "e", "o", "i", "u", "y"];

  // loop over array 's' in reverse. if the letter we're iterating over is in the vowels array, remove it. We do this in reverse because we'd skip letters if we went from front to back due to the splice.
  for (let i = s.length-1; i >= 0; i--) {
    if (vowels.indexOf(s[i]) > -1) {
      s.splice(i, 1); // 'i' is the index to start at (which we get from our loop) and 1 is the number of characters to remove.
    }
  }
  return s.join("");
}

console.log('tom => ' + removeVowels('tom'));
console.log('johnson => ' + removeVowels('johnson'));
console.log('aoeieyyozoyyeieoa => ' + removeVowels('aoeieyyozoyyeieoa'));

答案 2 :(得分:1)

由于执行后,

strAr.splice(i,1)
对于同一字符,原始字符串中的

index和strAr中的index不相同。 因此,您需要为此改变逻辑。

答案 3 :(得分:0)

这是使用Array.prototype.filterArray.prototype.joinArray.prototype.indexOf方法的更简单方法。以下代码还使用String.prototype.split方法将字符串转换为字符数组:

//1st param is the string you want to remove letters from
//2nd param is an array containing the letters to remove
function removeLetters(str, toRemove) {
  //Create an array - each index contains a single character
  let letters = str.split('');

  //Use Array.prototype.filter method to remove any letter that occurs in "toRemove" array
  let filtered = letters.filter(letter => toRemove.indexOf(letter) === -1)

  //Turn the filtered array back into a string
  return filtered.join('');
}

//The letters we want to remove are all vowels, so:
const vowels = ['a', 'e', 'i', 'o', 'u', 'y'];

//Some test cases
const word = "tommy";
const word2 = "johnson";
const word3 = "aeioux";
console.log(removeLetters(word, vowels));
console.log(removeLetters(word2, vowels));
console.log(removeLetters(word3, vowels));