我刚刚用javascript搞砸了,我只是想比较2个数组并从字符串中删除所有英语元音,以后再返回没有元音。
表示元音数组j
的迭代(arr
)会停止,但我希望它在i
的每次迭代时重新循环。
这是我的基本代码:
let sentence = 'eitan was here';
function disemvowel(str) {
let arr = ['a', 'e', 'i', 'o', 'u'];
let letters = str.split('');
let i, j;
for (i = 0, j = 0; i < letters.length && j < arr.length;) {
console.log('counter: i = ' + i + ', j = ' + j + ', ' + letters[i] + ' vs ' + arr[j] + 'and letters: ' + letters);
if (letters[i] == arr[j]) {
if (letters[i] == ' ') {
i++;
}
console.log('IF stopped here: ' + letters[i] + ' at i: ' + i + ', ' + arr[j] + ' at j: ' + j);
letters.splice(i, 1);
//console.log('letters after splice: '+ letters);
i++;
} else {
console.log('ELSE stopped here: ' + letters[i] + ' at i: ' + i + ', ' + arr[j] + ' at j: ' + j);
j++;
}
}
return letters;
}
console.log('letters are: ', disemvowel(sentence));
&#13;
j
。
答案 0 :(得分:3)
您无需循环以从字符串中删除元音。实现此目的的最佳方法是在replace()
中使用字符类,如此
let sentence = 'eitan was here';
sentence = sentence .replace(/[aeiou]/g,'');
您也可以像这样使用OR运算符(|)
sentence = sentence.replace(/a|e|i|o|u/g,'');
答案 1 :(得分:1)
sentence = 'eitan was here';
function disemvowel(str){
arr = ['a','e','i','o','u'];
arr.forEach((itm)=>{
var re = new RegExp(itm,'g');
str = str.replace(re,'');
})
return str;
}
console.log(disemvowel(sentence));
答案 2 :(得分:0)
你必须将j重置为0.此外,在这种情况下,你不能拼接你正在循环的相同数组,即字母数组。
<script>
let sentence = 'eitan was here';
function disemvowel(str) {
let arr = ['a', 'e', 'i', 'o', 'u'];
let letters = str.split('');
let output = [];
let i,j;
for (i=0,j=0; i<letters.length && j<arr.length;){
if(letters[i] == arr[j]){
j = 0;
i++;
}else{
j++;
if(j >= arr.length){
output.push(letters[i]);
i++;
j = 0;
}
}
}
return output;
}
console.log('letters are: ', disemvowel(sentence));
</script>