给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)

我认为每个美元可能有用,但我不确定如何实现它。


当前回答

var arr = [1, 2, 3, 4];
var total = 0;
for (var i in arr) {
  total += arr[i];
}

其他回答

此外,对于简单数组,使用es6求和。

const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0);
 
console.log(sum); 

对于具有默认初始化值的对象数组

const totalAmount = obj => 
    Object.values(obj).reduce((acc, { order_qty, mrp_price }) => 
    acc + order_qty * mrp_price, 0);
    
    console.log(totalAmount); 

我是JavaScript和一般编码的初学者,但我发现一种简单易行的方法可以将数组中的数字相加,如下所示:

    var myNumbers = [1,2,3,4,5]
    var total = 0;
    for(var i = 0; i < myNumbers.length; i++){
        total += myNumbers[i];
    }

基本上,我想贡献这一点,因为我没有看到很多不使用内置函数的解决方案,而且这种方法很容易编写和理解。

    <!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>

使用for循环:

const array = [1, 2, 3, 4];
let result = 0;

for (let i = 0; i < array.length - 1; i++) {
  result += array[i];
}

console.log(result); // Should give 10

甚至是forEach循环:

const array = [1, 2, 3, 4];
let result = 0;

array.forEach(number => {
  result += number;
})

console.log(result); // Should give 10

为简单起见,请使用reduce:

const array = [10, 20, 30, 40];
const add = (a, b) => a + b
const result = array.reduce(add);

console.log(result); // Should give 100

带ES6休息参数

让数组=[1,2,3,4]函数和(…数字){设总数=0;for(常量数){总数+=数量;}回报总额;}console.log(sum(…array));