繁体   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