我有问题添加一个数组的所有元素以及平均它们。我将如何做到这一点,并实现它与我目前的代码?元素的定义如下所示。
<script type="text/javascript">
//<![CDATA[
var i;
var elmt = new Array();
elmt[0] = "0";
elmt[1] = "1";
elmt[2] = "2";
elmt[3] = "3";
elmt[4] = "4";
elmt[5] = "7";
elmt[6] = "8";
elmt[7] = "9";
elmt[8] = "10";
elmt[9] = "11";
// Problem here
for (i = 9; i < 10; i++){
document.write("The sum of all the elements is: " + /* Problem here */ + " The average of all the elements is: " + /* Problem here */ + "<br/>");
}
//]]>
</script>
在支持es6的浏览器中,这个填充可能会有帮助。
Math.sum = (...a) => Array.prototype.reduce.call(a,(a,b) => a+b)
Math.avg = (...a) => Math.sum(...a)/a.length;
你可以在Math.sum和Math.sum之间共享相同的调用方法。avg和Math。马克斯,如
var maxOne = Math.max(1,2,3,4) // 4;
你可以用数学。总和为
var sumNum = Math.sum(1,2,3,4) // 10
或者如果你有一个数组要求和,你可以使用
var sumNum = Math.sum.apply(null,[1,2,3,4]) // 10
就像
var maxOne = Math.max.apply(null,[1,2,3,4]) // 4
这里是一个快速添加到“数学”对象在javascript中添加一个“平均”命令!!
Math.average = function(input) {
this.output = 0;
for (this.i = 0; this.i < input.length; this.i++) {
this.output+=Number(input[this.i]);
}
return this.output/input.length;
}
然后我有这个加法“数学”对象得到和!
Math.sum = function(input) {
this.output = 0;
for (this.i = 0; this.i < input.length; this.i++) {
this.output+=Number(input[this.i]);
}
return this.output;
}
那么你要做的就是
alert(Math.sum([5,5,5])); //alerts “15”
alert(Math.average([10,0,5])); //alerts “5”
我把占位符数组只是传递在你的变量(输入如果他们是数字可以是一个字符串,因为它解析到一个数字!)
只是为了好玩:
var elmt = [0, 1, 2,3, 4, 7, 8, 9, 10, 11], l = elmt.length, i = -1, sum = 0;
for (; ++i < l; sum += elmt[i])
;
document.body.appendChild(document.createTextNode('The sum of all the elements is: ' + sum + ' The average of all the elements is: ' + (sum / l)));