给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
arr.reduce(function (a, b) {
return a + b;
});
参考:Array.prototype.reduce()
其他回答
<!DOCTYPE html>
<html>
<body>
<p>Click the button to join two arrays.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var hege = [1, 2,4,6,7,8,8];
var stale = [1, 2,4,5];
function myFunction() {
console.log((hege.length > stale.length))
var children = (hege.length > stale.length)? abc1() :abc2(); document.getElementById("demo").innerHTML = children;
}
function abc1(){
console.log(hege,"Abc1")
var abcd=hege.map(function (num, idx) {
console.log(hege.length , idx)
return stale.length>idx?num + stale[idx]:num;
})
return abcd;
}
function abc2(){
console.log(hege,"Abc2",stale)
var abcd=stale.map(function (num, idx) {
console.log(hege.length , idx)
return hege.length>idx?num + hege[idx]:num;
})
return abcd;
}
</script>
</body>
</html>
一些人建议在Array.prototype中添加.sum()方法。这通常被认为是不好的做法,所以我不建议您这样做。
如果你仍然坚持这样做,那么这是一种简洁的写作方式:
Array.prototype.sum = function() {return [].reduce.call(this, (a,i) => a+i, 0);}
然后:[1,2].sum();//3.
注意,添加到原型中的函数使用了ES5和ES6函数以及箭头语法的混合。声明该函数是为了允许该方法从正在操作的Array中获取this上下文。为了简洁起见,我在reduce调用中使用了=>。
var total = 0;
$.each(arr,function() {
total += this;
});
Vanilla JavaScript是您所需要的一切:
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(function(e){sum += e}); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(e => sum += e); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e in a) sum += e; sum
"00123foobar"
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e of a) sum += e; sum
10
一个简单的方法示例:
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]));