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

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


当前回答

没有人提到函数式编程,但在这种情况下使用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));

其他回答

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

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

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

使用贴图:

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();
    <!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

当数组由字符串组成时,必须更改代码。如果数组是数据库请求的结果,则可能是这种情况。此代码有效:

alert(
["1", "2", "3", "4"].reduce((a, b) => Number(a) + Number(b), 0)
);

这里,[“1”,“2”,“3”,“4”]是字符串数组,函数Number()将字符串转换为数字。