对javascript构造函数中的参数求和并返回total
Sum the parameters in javascript constructor and return total
如果我有一个构造函数,并且想要将参数值求和并输出到一个内部方法,我认为我可以这样做:
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());
为了得到想要的输出
相关文章:
- 节点导出返回一个空对象
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 控制台返回var不是't定义,但它是
- 从函数返回角度承诺
- Javascript返回值只在循环中返回一次
- 从控制器返回后Ajax启动事件激发
- CKFinder 3为所选文件返回错误的URL
- 如何在d3.js中返回路径的y坐标
- 如何从jquery函数返回变量
- Angular js-返回一个包含类似
- 尝试求和时,在我的表的页脚中返回$NaN
- javascript 在求和时返回 NaN
- 求和所有输入值的方法总是返回0
- 如何以某种方式对post返回的数据求和
- 对javascript构造函数中的参数求和并返回total
- 在Elasticsearch Javascript客户端进行求和时返回的奇怪值
- 求和返回NaN
- 当对数组元素求和时,递归函数根据顺序返回不同的值
- 对象在求和时返回NaN