簡體   English   中英

Javascript 將除法 (/) 檢測為加法 (+)

[英]Javascript detects divide (/) as addition (+)

我正在嘗試使用對象制作一個基本的、基於 javascript 的計算器。 出於某種原因,屬性“calculator.divide”似乎返回了兩個數字的相加。

我已經在在線編譯器(js.do & code.sololearn.com)和記事本中嘗試過這個,但它似乎不起作用。

var n1 = +(prompt("Enter 1st number:"));
var n2 = +(prompt("Enter 2nd number:"));
//gets user input & declares variables
//+ for changing string to integer
var calculator = {
 add: (n1 + n2), subtract: (n1 - n2), multiply: (n1 * n2), divide: (n1 / n2)
};
var operation = prompt("enter an operation: add, subtract, multiply, or divide");
if (operation = "add") {
    document.write(calculator.add);
}
else if (operation = "subtract") {
    document.write(calculator.subtract);
}
 else if (operation = "multiply") {
    document.write(calculator.multiply);
}
 else if (operation = "divide") {
    document.write(calculator.divide);
}

例如,如果我輸入 6 作為我的第一個數字,輸入 2 作為我的第二個數字,據我所知,當訪問“calculator.divide”時它會輸出“3”。 情況似乎並非如此。 相反,它輸出“8”,就好像它正在添加它們一樣。

(operation = "add")是錯誤的,它必須是(operation === "add")if其余部分也是if 而不是進行比較,它只是分配值

 var n1 = +(prompt("Enter 1st number:")); var n2 = +(prompt("Enter 2nd number:")); //gets user input & declares variables //+ for changing string to integer var calculator = { add: (n1 + n2), subtract: (n1 - n2), multiply: (n1 * n2), divide: (n1 / n2) }; var operation = prompt("enter an operation: add, subtract, multiply, or divide"); if (operation === "add") { document.write(calculator.add); } else if (operation === "subtract") { document.write(calculator.subtract); } else if (operation === "multiply") { document.write(calculator.multiply); } else if (operation === "divide") { document.write(calculator.divide); }

您可以避免if-else並使用對象查找

 var n1 = +(prompt("Enter 1st number:")); var n2 = +(prompt("Enter 2nd number:")); var operation = prompt("enter an operation: add, subtract, multiply, or divide"); function execute(n1, n2, ops) { calculator = { add: (n1 + n2), subtract: (n1 - n2), multiply: (n1 * n2), divide: (n1 / n2), } return (calculator[ops]); } document.write(execute(n1, n2, operation.trim()))

您還可以避免內部計算功能

 var n1 = +(prompt("Enter 1st number:")); var n2 = +(prompt("Enter 2nd number:")); var operation = prompt("enter an operation: add, subtract, multiply, or divide"); function calculator(n1, n2, ops) { return { add: (n1 + n2), subtract: (n1 - n2), multiply: (n1 * n2), divide: (n1 / n2), }[ops]; } document.write(calculator(n1, n2, operation.trim()))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM