[英]check if last character of a string is a vowel in Javascript
I'm trying to make a beginner program that returns true if an inputted string ends with a vowel and false if not, but am having issues given endsWith() only allows to do one letter at a time.我正在尝试制作一个初学者程序,如果输入的字符串以元音结尾则返回 true,否则返回 false,但是我遇到了问题,因为 endsWith() 一次只允许一个字母。 messing around with if else options today didn't help me much and after a couple hours on one problem i'm ready for some help lol今天摆弄 if else 选项对我没有太大帮助,在解决一个问题几个小时后,我准备好寻求帮助了,哈哈
here's what i have so far:这是我到目前为止所拥有的:
console.log(x.endsWith("e"));
console.log(x.endsWith("i"));
console.log(x.endsWith("o"));
console.log(x.endsWith("u"));```
any help is appreciated thanks so much.非常感谢任何帮助。 we're supposed to have just one boolean value show up and I'm stumped我们应该只显示一个布尔值,但我很困惑
Just iterate through the vowels:只需遍历元音:
function endsVowel(str){
for (let i of "aeiou"){
if (str.endsWith(i)){
return true;
}
}
return false;
}
But am having issues given
endsWith()
only allows to do one letter at a time但是我遇到了问题,endsWith()
一次只允许写一个字母
So you should check the last char belongs to vowels - 'u', 'e', 'o', 'a', 'i'
or not in this way.所以你应该检查最后一个字符是否属于vowels - 'u', 'e', 'o', 'a', 'i'
或不这样。
const vowels = ['u', 'e', 'o', 'a', 'i']; const isVowelAtLastCharacter = (str) => { const lastChar = str.charAt(str.length - 1); return vowels.includes(lastChar); } console.log(isVowelAtLastCharacter("xu")); console.log(isVowelAtLastCharacter("xe")); console.log(isVowelAtLastCharacter("xo")); console.log(isVowelAtLastCharacter("xa")); console.log(isVowelAtLastCharacter("xi")); console.log(isVowelAtLastCharacter("xz"));
const isEndsWithVowel=(s)=>{
const vowelSet= new Set(['a','e','i','o','u']);
return vowelSet.has(s[s.length-1]);
}
you can follow this code, I hope can help you, after review of Phong您可以按照此代码进行操作,希望对您有所帮助,经过 Phong 审核
let word_to_review = "California";
function reverseArray(arr) {
var newArray = [];
for (var i = arr.length - 1; i >= 0; i--) {
newArray.push(arr[i]);
}
return newArray;
}
const getLastItem = reverseArray(word_to_review)[0];
let isVowel;
if (
getLastItem === "a" ||
getLastItem === "e" ||
getLastItem === "i" ||
getLastItem === "o" ||
getLastItem === "u"
) {
isVowel = true;
} else {
isVowel = false;
}
console.log(
"is the last letter is vowel, yes or no ? The answer is.... " + isVowel
);
Another possible solution -另一种可能的解决方案 -
let x = "India"
const vowels = ['a','e','i','o','u']; //add capital letters too if string has capital letters
if(vowels.includes(x[x.length-1])){
console.log('string ends with vowel', x);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.