对javascript构造函数中的参数求和并返回total

Sum the parameters in javascript constructor and return total

本文关键字:求和 返回 total 参数 javascript 构造函数      更新时间:2023-09-26

如果我有一个构造函数,并且想要将参数值求和并输出到一个内部方法,我认为我可以这样做:

function Stats(a, b, c, d, e, f) {
    this.a = a;
    this.b = b;
    this.c = c; 
    this.d = d; 
    this.e = e; 
    this.f = f;
    var total = 0;
    var array = [a, b, c, d, e, f];
    var len = array.length;
    this.sum = function() {
        for(var i = 0; i < len; i++) {
            total += array[i];
        }
        return total;
    };
}
var output = new Stats(10, 25, 5, 84, 8, 44);
console.log(output);

当查看控制台'total'为0时。

我确信我的逻辑完全失败了,所以如果你有建议如何改进这个(以及总和),我很乐意阅读它们。

可以缩写

function Stats(var_args) {
  var sum = 0;
  // The arguments pseudo-array allows access to all the parameters.
  for (var i = 0, n = arguments.length; i < n; ++i) {
    // Use prefix + to coerce to a number so that += doesn't do
    // string concatenation.
    sum += +arguments[i];
  }
  // Set the sum property to be the value instead of a method
  // that computes the value.
  this.sum = sum;
}
var output = new Stats(10, 25, 5, 84, 8, 44);
// You can use a format string to see the object and a specific value.
console.log("output=%o, sum=%d", output, output.sum);
function Stats(){
    var sum = 0;
    for (var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

Arguments变量以数组形式包含函数的所有参数。

不知道你想在这里实现什么但我认为它可能是有用的看看你的变量堆栈

可在jsfiddle上使用

function Stats(a, b, c, d, e, f) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.sum = Array.prototype.reduce.call(arguments, function (x, y) {
        return x + y;
    }, 0);
}
var output = new Stats(10, 25, 5, 84, 8, 44);
console.log(output);

您必须调用sum - output是对象:

console.log(output.sum());

,为了改进你的类,我要做一些更一般的事情,不限制参数的个数,如果我想做的只是对它们求和:

    function Stats() {
        this.total = (function(args){
            var total = 0;
            for(var i = 0; i < args.length; i++) {
                total += args[i];
            }
            return total;
        })(arguments);
     }
var output = new Stats(10, 10, 5, 10, 10, 10,100,24,1000);
console.log(output.total);

我认为这是你想要的优化版本:

function Stats() {
    var _arguments = arguments;
    this.sum = function() {
        var i = _arguments.length;
        var result = 0;
        while (i--) {
            result += _arguments[i];
        }
        return result;
    };
}
var output = new Stats(10, 25, 5, 84, 8, 44);
console.log(output.sum());

根据您编写代码的方式,您应该执行

console.log(output.sum());

为了得到想要的输出