2 回答

TA貢獻1828條經驗 獲得超3個贊
我希望我能更好地理解這個問題,但我根據 Jaromanda X 的觀察更新了您的 IF-ELSE 邏輯。
=
僅用于賦值,不應用于檢查相等性。相反,當嘗試評估多個值的相等性時,您應該使用==
或。
下面是編譯和運行的代碼的更新版本,但同樣,我不確定預期結果到底是什么,所以我會讓您確定它現在是否按預期工作。
<script>
? ? var operators = ['+', '-'];
? ? var e = ['km', 'm'];
? ? function F1() {
? ? ? ? num1 = document.getElementById("num1");
? ? ? ? num2 = document.getElementById("num2");
? ? ? ? rnum1 = Math.floor((Math.random() * 10) + 1);
? ? ? ? rnum2 = Math.floor((Math.random() * 10) + 1);
? ? ? ? num1.innerHTML = rnum1;
? ? ? ? num2.innerHTML = rnum2;
? ? ? ? oper = document.getElementById("operator");
? ? ? ? op = operators[Math.floor(Math.random() * 2)];
? ? ? ? oper.innerHTML = op;
? ? ? ? eht = document.getElementById("e1");
? ? ? ? eht2 = document.getElementById("e2");
? ? ? ? eh = e[Math.floor(Math.random() * e.length)];
? ? ? ? eh2 = e[Math.floor(Math.random() * e.length)];
? ? ? ? eht.innerHTML = eh;
? ? ? ? eht2.innerHTML = eh2;
? ? ? ? answer = document.getElementById("answer");
? ? ? ? if (eh === 'km') {
? ? ? ? ? ? if (eh2 === 'm') {
? ? ? ? ? ? ? ? answer.innerHTML = eval(rnum1 * 1000 + op + rnum2);
? ? ? ? ? ? }
? ? ? ? ? ? else {
? ? ? ? ? ? ? ? if (eh === 'm') {
? ? ? ? ? ? ? ? ? ? if (eh2 === 'km') {
? ? ? ? ? ? ? ? ? ? ? ? answer.innerHTML = eval(rnum1 + op + rnum2 * 1000);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? else {
? ? ? ? ? ? ? ? ? ? ? ? if (eh === 'km') {
? ? ? ? ? ? ? ? ? ? ? ? ? ? if (eh2 === 'km') {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? answer.innerHTML = eval(rnum1 * 1000 + op + rnum2 * 1000);
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? else {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? answer.innerHTML = eval(rnum1 + op + rnum2)
? ? ? ? ? ? ? ? ? ? ? ? ? ? };
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }
</script>
<p>
? ? <label id="num1"> </label> <label id="e1"> </label>
? ? <label id="operator"> </label>
? ? <label id="num2"> </label> <label id="e2"> </label>
? ? = <label id="answer">m </label>
</p>
<button onclick="F1()"> New </button>

TA貢獻1868條經驗 獲得超4個贊
我意識到對于我試圖創建的內容,我不需要添加else聲明。所以我if else用下面的代碼替換了所有語句,然后它就起作用了:
if (eh === 'km')
{if (eh2 === 'm')
{answer.innerHTML = eval(rnum1 * 1000 + op + rnum2);}}
if (eh === 'm')
{if (eh2 === 'km')
{answer.innerHTML = eval(rnum1 + op + rnum2 * 1000);}}
if (eh === 'km')
{if (eh2 === 'km')
{answer.innerHTML = eval(rnum1 * 1000 + op + rnum2 * 1000);}}
if (eh === 'm')
{if (eh2 === 'm')
{answer.innerHTML = eval(rnum1 + op + rnum2);}}
- 2 回答
- 0 關注
- 165 瀏覽
添加回答
舉報