[英]How do I create a function that accepts multiple arguments to perform an arithmetic calculation in JavaScript?
I want to write a function that performs arithmetic on ALL the arguments supplied.我想编写一个对提供的所有参数执行算术运算的函数。 So for instance, if I do:
例如,如果我这样做:
calculate('+', 3, 5, 6)
It should return 14 (which is 3+5+6)它应该返回 14(即 3+5+6)
Or if I do或者如果我这样做
calculate('*', 6,3,6,8,)
It should return 864 (which is the equivalent of multiplying all those numbers).它应该返回 864(相当于将所有这些数字相乘)。
The function should essentially be able to handle any amount of numbers I supply to it, while also being able to handle the main arithmetic operators such as + - / *该函数本质上应该能够处理我提供给它的任何数量的数字,同时还能够处理主要的算术运算符,例如 + - /*
I'm new at programming.我是编程新手。 I've tried:
我试过了:
function mCalc(_operator){
if(_operator=='+'){
return arguments + arguments;
}
}
console.log(mCalc('+',5,5));
this is not working so i can't even move forward.这不起作用,所以我什至无法前进。
In each function you have an arguments object see the section Rest, default, and destructured parameters as it states:在每个函数中,您都有一个参数对象,请参阅Rest、default 和 destructured parameters部分,因为它指出:
The arguments object can be used in conjunction with rest, default, and destructured parameters.
arguments 对象可以与 rest、default 和 destructured 参数结合使用。
function foo(...args) { return args; }
Once you have all the arguments which are needed for your calculation just use Array.prototype.reduce()
.一旦您拥有计算所需的所有参数,只需使用
Array.prototype.reduce()
。 As the documentation which states:正如文件所述:
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
reduce() 方法在数组的每个元素上执行一个 reducer 函数(您提供的),从而产生单个输出值。
I guess you can use as the following:我想你可以使用如下:
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);
I hope that helps!我希望这有帮助!
You could take an object for the operators and reduce the values by using a function which returns a function for two operands.您可以为运算符获取一个对象并通过使用返回两个操作数的函数的函数来减少值。
By calling the function the operator is taken and the values are taken to an array by using rest parameters ...
.通过调用该函数,运算符被采用,并且值通过使用其余参数被带到数组中
...
This approach uses arrow functions , like这种方法使用箭头函数,例如
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.