gpt4 book ai didi

javascript - while 循环在 JavaScript 中在新行上打印元音和其他元素

转载 作者:行者123 更新时间:2023-12-01 00:44:29 25 4
gpt4 key购买 nike

尝试按照单词出现的顺序在新行中打印单词中的任何元音。然后在打印所有元音后对每个常量执行相同的操作。

我尝试使用中断和开关盒,但代码不起作用。

function vowelsAndConsonants(s) {
var atom = s.length;
var i = 0;
while (i <= atom)
{
if (s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' || s[i] === 'u') {
console.log('\n' + s[i]);
}
else {
console.log('\n' + s);
}
}

}

我希望输出如下:

a
i
o

然后按辅音出现的顺序排列:

t
p
r

最佳答案

您可以使用includes来检查给定字符串上的元音数组

const vowelsAndconsonants = str => {
const vowels=['a','e','i','o','u'];
//convert string to array and get rid of non alphabets as we are just interested on consonants and vowel
const str_array=str.replace(/[^a-zA-Z]/g, '').split('');
//pluck vowels
const vowels_final=str_array.filter( a => vowels.includes(a.toLowerCase()));
//pluck consonants
const consonant_final=str_array.filter( a => !vowels.includes(a.toLowerCase()));
//to print any vowels from a word on a new line and then consonant in the order they appear.
return vowels_final.join('\n') + '\n' + consonant_final.join('\n');
}

console.log(vowelsAndconsonants('tEstOnlY and nothing else'))
console.log(vowelsAndconsonants('dry'))
console.log(vowelsAndconsonants('I love stackoverflow'))

关于javascript - while 循环在 JavaScript 中在新行上打印元音和其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57503603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com