我创建了一个函数,该函数使用字符串将字符串转换为数组,然后将每个字符串字符与数组中的每个元音进行比较,如果匹配,则删除该字符串字符。在更长的单词上似乎无法正常工作。例如,使用“ 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'));Run Code Online (Sandbox Code Playgroud)
问题是您打电话给strAr.splice(i,1);。
因此,您有单词“ johnson”,并且在删除第一个“ o”之后得到了“ jhnson”,但是当前字符串的长度是6而不是开头的7!
当您到达下一个“ o”时-的i值为5(对于“ johnson”字符串正确,但对“ jhnson”不是正确的)。
另外,循环中还有另一个错误-您有condition 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'));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |