我正在解决以下问题:编写一个程序,将第一个参数作为“sum”,“product”,“mean”或“sqrt”之一,并进一步论证一系列数字。该程序将适当的功能应用于该系列。
我已经解决了它(下面的代码)但它体积庞大且效率低下。我想重新编写它有一个功能计算器调用其他功能(即功能总和,功能产品)。< / p>
我的问题:如何编写函数sum,product,sqrt等,所以当函数计算器调用时,它们会正确地获取计算器的参数并计算数学。
以下是庞大的代码:
function calculator() {
var sumTotal = 0;
var productTotal = 1;
var meanTotal = 0;
var sqrt;
if(arguments[0] === "sum") {
for(i = 1; i < arguments.length; i++) {
sumTotal += arguments[i];
}
return sumTotal;
}
if(arguments[0] === "product") {
for(i = 1; i < arguments.length; i++) {
productTotal *= arguments[i];
}
return productTotal;
}
if(arguments[0] === "mean") {
for(i = 1; i < arguments.length; i++) {
meanTotal += arguments[i];
}
return meanTotal / (arguments.length-1);
}
if(arguments[0] === "sqrt") {
sqrt = Math.sqrt(arguments[1]);
}
return sqrt;
}
calculator("sqrt", 17);
答案 0 :(得分:8)
你可以用你需要的函数创建一个对象,然后让计算器函数调用正确的函数。
var operations = {
sum: function() { /* sum function */ },
product: function() { /* product function */ },
mean: function() { /* mean function */ },
sqrt: function() { /* sqrt function */ }
};
function calculator(operation) {
operation = operations[operation];
var args = Array.prototype.slice.call(arguments, 1);
return operation.apply(this, args);
}
You can see an example of this in action on jsFiddle
如果您不太了解我在代码中所做的事情,我建议您阅读call
and apply
in Javascript以及objects in Javascript。
答案 1 :(得分:2)
您可以使用apply()
方法将整个参数列表传递给另一个函数:
if(arguments[0] === "sum") {
return sum.apply(this, Array.prototype.slice.call(arguments, 1));
}
使用不同的方法进行操作:
function sum() {
var sumTotal = 0;
for(i = 1; i < arguments.length; i++) {
sumTotal += arguments[i];
}
return sumTotal;
}