给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
<!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>
其他回答
没有人提到函数式编程,但在这种情况下使用Ramda是非常干净的方法:
//Assuming you use nodejs, but can also be used in browser
const R = require('ramda');
let nums = [2, 4, 6, 8, 10];
console.log(R.sum(nums));
这里很酷的技巧,我对很多安全的传统答案进行了吹毛求疵,没有缓存数组的长度。
function arraySum(array){
var total = 0,
len = array.length;
for (var i = 0; i < len; i++){
total += array[i];
}
return total;
};
var my_array = [1,2,3,4];
// Returns 10
console.log( arraySum( my_array ) );
在不缓存数组长度的情况下,JS编译器需要在循环的每次迭代中遍历数组来计算长度,这在大多数情况下是不必要的开销。V8和许多现代浏览器都为我们优化了这一点,因此它不再那么受关注,但也有一些较旧的设备受益于这种简单的缓存。
如果长度可能会发生变化,如果您不知道为什么要缓存长度,缓存可能会导致一些意想不到的副作用,但对于唯一目的是获取数组并将值相加的可重用函数来说,这非常适合。
这里是这个arraySum函数的CodePen链接。http://codepen.io/brandonbrule/pen/ZGEJyV
这可能是一种过时的心态,一直困扰着我,但我不认为在这种情况下使用它有什么缺点。
var total = 0;
$.each(arr,function() {
total += this;
});
了解底层流程的最简单答案:
let array = [10, 20, 30, 40, 50]
let total = 0
for(let i in array)
{
total += array[i]
}
console.log(total)
&如果您已经熟悉底层流程,那么内置方法可以节省您的时间:
let array = [10, 20, 30, 40, 50]
let total = array.reduce((x, y) => x + y)
console.log(total)
事实上,有一个古老而有趣的经典解决方案(除了新手“foreach”和“reduce”):的经典。
y = 0;
for (x of [1, 2, 3, 4]) y+=x;