我试图找出我在这段代码中做错了什么。我正在尝试创建一个问题,向用户展示相等和不相等在 JS 中的工作原理,他们可以输入两个值并从下拉菜单中选择一个运算符。控制台日志有一个错误:
Uncaught SyntaxError: expected expression, got '='final.js:21:94
。看起来我可能无法将 =
、==
或 ===
运算符放入 ${}
?
function compareAnswer() {
let numberInput = parseInt(document.getElementById("value1").value);
let stringInput = (document.getElementById("value2").value);
let operator = document.getElementById("operator");
let answer = document.getElementById("answer");
let result;
if (operator.value == "=") {
result = `Value 1 was ${numberInput}, and is now ${numberInput = stringInput}.`;
} else if (operator.value == "==") {
result = `Are ${numberInput} and ${stringInput} equal? ${numberInput == stringInput}.`;
} else if (operator.value == "===") {
result = `Are ${numberInput} and ${stringInput} strict equal? ${numberInput === stringInput}.`;
} else if (operator.value == "not=") {
result = `Are ${numberInput} and ${stringInput} and has not changed ${numberInput != stringInput}.`;
} else if (operator.value == "not==") {
result = `Are ${numberInput} and ${stringInput} not equal? ${numberInput !== stringInput}.`;
} else if (operator.value == "not===") {
result = `Are ${numberInput} and ${stringInput} not strict equal? ${numberInput !=== stringInput}.`;
} else {
default = "try again."
}
answer.textContent = result;
console.log(`working`);
}
document.getElementById("compareButton").addEventListener("click", compareAnswer);
<div id="wrapper">
<div id="question6">
<h2>Question 6</h2>
<h3>Create a value that equals true with one of the operators.</h3>
<lable for="value">Value 1 </lable><input type="number" id="value1">
<br>
<br>
<lable for="value">Value 2 </lable><input type="text" id="value2">
<br>
<select id="operator">
<option value="="> = </option>
<option value="=="> == </option>
<option value="==="> == </option>
<option value="not="> != </option>
<option value="not=="> !== </option>
<option value="not==="> !=== </option>
</select>
<br>
<button id="compareButton">Equals</button>
<p id="answer">Answer</p>
</div>
</div>
在js中,严格相等是
===
,但严格不等只是!==
,而不是!===
。
所以你会得到一个错误
result = `Are ${numberInput} and ${stringInput} not strict equal? ${numberInput !=== stringInput}.`;
可以是
result = `Are ${numberInput} and ${stringInput} not strict equal? ${numberInput !== stringInput}.`;