簡體   English   中英

如何創建一個接受多個參數的函數以在 JavaScript 中執行算術計算?

[英]How do I create a function that accepts multiple arguments to perform an arithmetic calculation in JavaScript?

我想編寫一個對提供的所有參數執行算術運算的函數。 例如,如果我這樣做:

calculate('+', 3, 5, 6)

它應該返回 14(即 3+5+6)

或者如果我這樣做

calculate('*', 6,3,6,8,)

它應該返回 864(相當於將所有這些數字相乘)。

該函數本質上應該能夠處理我提供給它的任何數量的數字,同時還能夠處理主要的算術運算符,例如 + - /*

我是編程新手。 我試過了:

function mCalc(_operator){
  if(_operator=='+'){
    return arguments + arguments;
  }

}
console.log(mCalc('+',5,5));

這不起作用,所以我什至無法前進。

在每個函數中,您都有一個參數對象,請參閱Rest、default 和 destructured parameters部分因為它指出:

arguments 對象可以與 rest、default 和 destructured 參數結合使用。

function foo(...args) { return args; }

一旦您擁有計算所需的所有參數,只需使用Array.prototype.reduce() 正如文件所述:

reduce() 方法在數組的每個元素上執行一個 reducer 函數(您提供的),從而產生單個輸出值。

我想你可以使用如下:

 const mCalc = (_operator, ...args) => { if(_operator === '+') { return args.reduce((a, c) => a + c, 0); } // rest what you want to implement } const result = mCalc('+', 3, 5, 6, 2); console.log(result);

我希望這有幫助!

您可以為運算符獲取一個對象並通過使用返回兩個操作數的函數的函數來減少值。

通過調用該函數,運算符被采用,並且值通過使用其余參數被帶到數組中...

這種方法使用箭頭函數,例如

calculate = (op, ...values) => values.reduce(take(op));
^^^^^^^^^                                               name of the function/variable
            ^^^^^^^^^^^^^^^                             parameters
                            ^^                          arrow
                               ^^^^^^^^^^^^^^^^^^^^^^^  return value

 const operators = { '+': (a, b) => a + b, '*': (a, b) => a * b }, take = op => operators[op], calculate = (op, ...values) => values.reduce(take(op)); console.log(calculate('+', 3, 5, 6)); // 14 console.log(calculate('*', 6, 3, 6, 8));

暫無
暫無

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

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