[英]If variable is equal to value or another value - javascript
I'm trying to write a simple Pig Latin code. 我正在尝试编写一个简单的Pig Latin代码。 I want to check if the first letter of the input string is a vowel, if so then to run that certain code.
我想检查输入字符串的第一个字母是否是元音,如果是,则运行该特定代码。 How can I ask if y is equal to one of those values.
我怎么问y是否等于这些值之一。
function pigLatin() {
var y = prompt("Enter a word:")
if (y.charAt(0) = a,e,i,o,u) {
var pigLatin = y + "ay";
document.getElementById("answer").innerHTML = "Answer is: " + pigLatin;
} else {
var wordLength = y.length + 1;
var pigLatin = y.substring(1, wordLength) + y.charAt(0) + "ay";
document.getElementById("answer").innerHTML = "Answer is: " + pigLatin;
}
}
if (y.charAt(0) = a,e,i,o,u) {
...is not valid. ...无效。
Try... 尝试...
if ('aeiou'.includes(y.charAt(0))) {
Your problems are... 你的问题是...
[
and ]
(unless constructed via another means such as with the Array
constructor) [
和]
包裹(除非通过其他方法(例如Array
构造函数)构造) =
), nor any equivalency operator ( ==
or ===
) to automatically check for the presence of an item in an array. =
),也不能使用任何等效运算符( ==
或===
)自动检查数组中是否存在项。 Since you're checking against a list of single characters, you can directly use String.prototype.includes()
on it. String.prototype.includes()
。 If the user cancels the prompt()
, you will get null
also, which you are not handling (it will crash on the condition mentioned). 如果用户取消了
prompt()
,那么您也将得到null
,这不是您要处理的(它将在提到的条件下崩溃)。
First, you need the letters to be in quotes in this 首先,您需要将字母用引号引起来
if (y.charAt(0) = a,e,i,o,u)
Second, use ===
for equals. 其次,将
===
用于等于。
Third you want it to be one of the vowels 'a', 'e', 'i', 'o', 'u'. 第三,您希望它成为元音“ a”,“ e”,“ i”,“ o”,“ u”之一。
You could compare the indexOf
the char against -1: 您可以将char的
indexOf
与-1比较:
if (['a', 'e', 'i', 'o', 'u'].indexOf(y.charAt(0)) !== -1)
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.