在JavaScript中检查元音时Pig Latin Defective If语句



我正在为一个编程研讨会制作一个pig拉丁翻译程序,但在检查单词的第一个字母是否为元音时,我使用的if语句遇到了问题。即使我特别指出布尔"isVowel"是假的,它仍然会打印出bananaway,元音的翻译,而不是ananabay,辅音的翻译。

var button = document.getElementById("button");
var input = document.getElementById("input");
button.addEventListener("click", function(){

var original = String(input.value);
var translated = "";
originalArray = original.split(" ");

for (var index = 0; index < originalArray.length; index++) {
var word = originalArray[index];
var wordFirstIndex = word[0];
var rootWord = word.substr(1);
var isVowel = false;

if (wordFirstIndex = "a") {
isVowel = true;
} else if (wordFirstIndex = "e") {
isVowel = true;
} else if (wordFirstIndex = "i") {
isVowel = true;
} else if (wordFirstIndex = "o") {
isVowel = true;
} else if (wordFirstIndex = "u") {
isVowel = true;
} else {
isVowel = false;
}
if (isVowel = true) {
translated += word + "way" + " ";
} else if (!isVowel) {
translated += rootWord + wordFirstIndex + "ay" + " ";
}
}
var output = document.getElementById("output").innerHTML = translated;
});
body {
font-family: courier new;
}
#button {
color: white;
background-color: blue;
border: none;
padding: 5px 10px;
font-family: courier new;
}
#input {
padding: 10px 20px;
border: 2px;
border-style: solid;
border-color: skyblue;
}
#section1 {
font-size: 15px;
}
#output {
padding: 5px 50px; 
font-size: 13px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<pre>
<textarea id="input" rows="5" cols="40"></textarea>
<button id="button">Translate</button>
<section id="section1">
New text:
<p id="output"></p>
</pre>
</section>
<script src="script.js"></script>
</pre>
</body>
</html>

您的问题出现在所有if语句中。

  1. if (isVowel = true)应为if (isVowel === true)或仅为if (isVowel)
  2. 对于CCD_ 5和低于该值的所有CCD_。只需在===上替换=即可

为什么执行if (wordFirstIndex = "a")时,将新值附加到变量wordFirstIndex。这就是问题所在。要比较两个对象,应使用运算符=====(首选)。请参阅此答案以获取有关=====之间差异的更多信息。

最新更新