给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
这正是减薪的工作。
如果您使用的是ECMAScript 2015(又名ECMAScript6):
constsum=[1,2,3]。reduce((partialSum,a)=>partialSum+a,0);console.log(总和);//6.
对于旧的JS:
常量sum=[1,2,3]。reduce(add,0);//数组为空时避免使用初始值函数add(累加器,a){返回蓄能器+a;}console.log(总和);//6.
这不是很漂亮吗?:-)
其他回答
<!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>
对于真正大量的人来说,循环或减少可能是过程密集型的。使用高斯怎么样?
sum = (n * (n+1))/2;
来自mathcentral。
这些都是很好的答案,但如果数字是按照问题(1,2,3,4)中的顺序排列的话,你可以通过应用公式轻松地做到这一点(n*(n+1))/2,其中n是最后一个数字
一小段JavaScript代码就能完成这项工作:
var numbers = [1,2,3,4];
var totalAmount = 0;
for (var x = 0; x < numbers.length; x++) {
totalAmount += numbers[x];
}
console.log(totalAmount); //10 (1+2+3+4)
使用reduce
设arr=[1,2,3,4];设和=arr.reduce((v,i)=>(v+i));console.log(总和);