JS比较函数语法报错排查:模板字符串运算符使用疑问
问题修复方案
核心错误分析
你的控制台报错Uncaught SyntaxError: expected expression, got '='主要由以下几个问题导致:
1. 无效的运算符!===
JavaScript中不存在!===这个运算符,严格不相等的正确写法是!==。代码里numberInput !=== stringInput这一行完全违反语法规则,是直接触发报错的核心原因。
2. 错误使用关键字default
在else分支里,你写了default = "try again.",但default是JavaScript的保留关键字,不能当作变量名使用,应该直接给result赋值。
3. 模板字符串内赋值的潜在问题
虽然ES6允许在模板字符串的${}表达式中使用赋值语句,但这种写法可读性差,且容易引发解析器混淆。建议先完成赋值操作,再将变量插入模板。
4. 额外的小问题
- HTML中
<lable>拼写错误,正确标签是<label> - 下拉菜单里
value="==="的选项显示文本是==,与实际value不匹配,会误导用户 - 下拉菜单里的
not===选项对应的运算符不存在,属于无效选项
修正后的完整代码
JavaScript代码
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 === "=") { numberInput = stringInput; result = `Value 1 was ${numberInput}, and is now ${numberInput}.`; } 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} not equal? ${numberInput != stringInput}.`; } else if (operator.value === "not==") { result = `Are ${numberInput} and ${stringInput} not strict equal? ${numberInput !== stringInput}.`; } else { result = "Try again."; } answer.textContent = result; console.log("working"); } document.getElementById("compareButton").addEventListener("click", compareAnswer);
HTML代码
<div id="wrapper"> <div id="question6"> <h2>Question 6</h2> <h3>Create a value that equals true with one of the operators.</h3> <label for="value1">Value 1 </label><input type="number" id="value1"> <br><br> <label for="value2">Value 2 </label><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> </select> <br> <button id="compareButton">Equals</button> <p id="answer">Answer</p> </div> </div>
内容的提问来源于stack exchange,提问作者lschmi
相关产品推荐
相关产品推荐

