gpt4 book ai didi

JavaScript(初级)Kata - 使用函数构建计算器

转载 作者:数据小太阳 更新时间:2023-10-29 05:55:51 26 4
gpt4 key购买 nike

我正在解决以下问题:编写一个程序,将单词“sum”、“product”、“mean”或“sqrt”中的一个作为第一个参数,进一步的参数是一系列数字。该程序将适当的功能应用于该系列。

我已经解决了它(下面的代码),但它体积庞大且效率低下。我希望重新编写它,使其具有调用其他函数(即函数 sum、函数 product)的单个函数 calculator

我的问题:我如何编写函数 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);

最佳答案

您可以只创建一个包含所需函数的对象,然后让计算器函数调用正确的函数。

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 .

关于JavaScript(初级)Kata - 使用函数构建计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9729963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com