给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
使用贴图:
var sum = 0;
arr.map(function(item){
sum += item;
});
// sum now contains the total.
您可以将该方法添加到Array原型中。
Array.prototype.sum = function(){
var sum = 0;
this.map(function(item){
sum += item;
});
return sum;
}
然后您可以在任何阵列上使用它,如下所示:
arr.sum();
其他回答
var totally = eval(arr.join('+'))
这样你就可以在阵列中放置各种各样的异国情调的东西。
var arr = ['(1/3)','Date.now()','foo','bar()',1,2,3,4]
我只是半开玩笑。
var total = 0;
$.each(arr,function() {
total += this;
});
我看到这是一个老问题,但几乎没有任何答案实际使用jQuery,特别是按照提问者的要求使用$.each。有一种方法可以做到这一点,但许多人建议的本机方法(即使用Array.reduce())要好得多,也更容易。
如果您必须使用jQuery,请使用以下方法:
var arr = [1,2,3,4];
var sum = 0;
$.each( arr, (i, v) => sum += v);
alert(sum); // This will be 10
是否有理由不首先过滤数组以删除非数字?看起来很简单:
[1, 2, 3, null, 'a'].filter((x) => !isNaN(x)).reduce((a, b) => a + b)
<!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>