我正在解决以下问题: 编写一个程序,其中第一个参数是"sum","product","mean"或"sqrt"之类的单词,以及一系列数字的进一步参数.该程序将适当的功能应用于该系列.
我已经解决了它(下面的代码)但它体积庞大且效率低下.我想重写它有一个功能计算器,调用其他功能(即功能和,功能产品).
我的问题:我如何编写函数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);
Run Code Online (Sandbox Code Playgroud)
您可以使用所需的函数创建一个对象,然后让计算器函数调用正确的函数.
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);
}
Run Code Online (Sandbox Code Playgroud)
如果你不很明白我在我的代码正在做的,我建议阅读call和applyJavascript中,也约在Javascript对象.
| 归档时间: |
|
| 查看次数: |
2744 次 |
| 最近记录: |