簡體   English   中英

在 Javascript 中,簡單的計算器,不工作

[英]In Javascript, simple calculator, not working

我試圖通過 prompt() 和動作名稱來獲取數字。 但結果並不如預期

我是編程新手.. 代碼:

function add(n1, n2){   return n1 + n2;}

function sub(n1, n2){   return n1 - n2;}

function mult(n1, n2){  return n1 * n2;}

function div(n1, n2){   return n1/n2;}


function calculator(n1, n2, action){

    alert(action(n1, n2));
}

calculator(prompt("first no,"), prompt("second No"), prompt("calc"));

你需要做兩件事:

  1. 將輸入解析為浮點數
  2. Map function 用戶給定的名稱

 function add(n1, n2) { return n1 + n2; } function sub(n1, n2) { return n1 - n2; } function mult(n1, n2) { return n1 * n2; } function div(n1, n2) { return n1 / n2; } function calculator(n1, n2, action) { alert(action(n1, n2)); } function findOperation(name) { switch (name) { case "sub": return sub; case "mult": return mult; case "div": return div; case "add": default: return add; } } calculator( parseFloat(prompt("first no,")), parseFloat(prompt("second No")), findOperation(prompt("Operation Name?")) );

我建議您花時間學習一些基礎知識,除非您像這樣使用 eval(),否則您無法將字符串轉換為 function 調用:

function add(n1, n2){ return n1 + n2;}
function sub(n1, n2){ return n1 - n2;}
function mult(n1, n2){ return n1 * n2;}
function div(n1, n2){ return n1/n2;}

function calculator(n1, n2, action){
alert(eval(`${action}(${n1}, ${n2})`));
}

calculator(prompt("first no,"), prompt("second No"), prompt("calc"));

但這確實是 hacky 和不安全的代碼,更好的方法是:

const ops = {
"add": (n1, n2) => n1 + n2,
"sub": (n1, n2) => n1 - n2,
"mult": (n1, n2) => n1 * n2,
"div": (n1, n2) => n1/n2
}

function calculator(n1, n2, action){
alert(ops[action](parseFloat(n1), parseFloat(n2)));
}

calculator(prompt("first no,"), prompt("second No"), prompt("calc"));

還要注意 parseFloat(),如果你將參數保存為字符串,你會得到:

input: "1", "2", "add" output: "12"

計算器 function 應該是:

function calculator(n1, n2, action){

    alert(eval(action+'('+n1+', '+n2+')'));
}

暫無
暫無

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

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