给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
一个“重复”问题问如何对二维数组执行此操作,因此这是一个简单的适应问题。(区别仅在于六个字符[2],0,它在每个子数组中找到第三项,并传递初始值0):
常量二维数组=[[10, 10, 1],[10, 10, 2],[10, 10, 3],];constsum=twoDimensionalArray.reduce((partial_sum,a)=>partial_sum+a[2],0);console.log(总和);//6.
其他回答
Object.defineProperty(Object.prototype, 'sum', {
enumerable:false,
value:function() {
var t=0;for(var i in this)
if (!isNaN(this[i]))
t+=this[i];
return t;
}
});
[20,25,27.1].sum() // 72.1
[10,"forty-two",23].sum() // 33
[Math.PI,0,-1,1].sum() // 3.141592653589793
[Math.PI,Math.E,-1000000000].sum() // -999999994.1401255
o = {a:1,b:31,c:"roffelz",someOtherProperty:21.52}
console.log(o.sum()); // 53.519999999999996
您可以使用for of循环求和,如下所示:
let arr = [1, 2, 3, 4];
let total = 0;
for (let i of arr) {
total += i;
}
console.log(total)
getTotal = (arr) => {
let total = 0
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total
}
getTotal([1, 2, 3, 4]) // 10
getTotal([1, 2, 3, 4, 5]) // 15
可以将reduce()方法与lambda表达式结合使用:
[1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);
一个简单的方法示例:
function add(array){
var arraylength = array.length;
var sum = 0;
for(var timesToMultiply = 0; timesToMultiply<arraylength; timesToMultiply++){
sum += array[timesToMultiply];
}
return sum;
}
console.log(add([1, 2, 3, 4]));