检查字符串的最后一个字符是否是Javascript中的元音

问题描述

我正在尝试编写一个初学者程序,如果输入的字符串以元音结尾,则返回 true,否则返回 false,但我遇到了问题,endsWith() 一次只允许输入一个字母。今天弄乱了 if else 选项对我没有多大帮助,在一个问题上几个小时后,我准备好寻求帮助了,哈哈

这是我目前所拥有的:

console.log(x.endsWith("e"));
console.log(x.endsWith("i"));
console.log(x.endsWith("o"));
console.log(x.endsWith("u"));```

非常感谢任何帮助。我们应该只显示一个布尔值,我很难过

解决方法

只需遍历元音:

function endsVowel(str){
    for (let i of "aeiou"){
        if (str.endsWith(i)){
            return true;
        }
    }
    return false;
}
,

但是我遇到了问题 endsWith() 只允许在 一段时间

因此您应该以这种方式检查最后一个字符是否属于 vowels - 'u','e','o','a','i'

const vowels = ['u','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','i','u']);

    return vowelSet.has(s[s.length-1]);
}
,

您可以按照此代码进行操作,希望对您有所帮助,经过 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
);