给定一个数组[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>

其他回答

这可以通过循环所有项,并在每次迭代中将它们添加到一个和变量中来实现。

var array = [1, 2, 3];

for (var i = 0, sum = 0; i < array.length; sum += array[i++]);

JavaScript不知道块的作用域,所以可以访问sum:

console.log(sum); // => 6

同上,但注释和准备为简单函数:

function sumArray(array) {
  for (
    var
      index = 0,              // The iterator
      length = array.length,  // Cache the array length
      sum = 0;                // The total amount
      index < length;         // The "for"-loop condition
      sum += array[index++]   // Add number on each iteration
  );
  return sum;
}

带reduce()

[1, 2, 3, 4].reduce((a, b) => a + b, 0); // 10

使用forEach()

let sum = 0;
[1, 2, 3, 4].forEach(n => sum += n);
sum; // 10

带参数

function arrSum(arr) { 
  sum = 0;  
  arr.forEach(n => sum += n); 
  return sum; 
}

arrSum([1, 2, 3, 4]) // 10

是否有理由不首先过滤数组以删除非数字?看起来很简单:

[1, 2, 3, null, 'a'].filter((x) => !isNaN(x)).reduce((a, b) => a + b)

一小段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)

非常简单

步骤1我们应该有一个数组,如:

const arrayNumber = [500,152,154,1555,12445];

第2步(如果需要,可以忽略这个步骤)要确保表中的所有值都是数字

let newArray = [];
for (let i = 0; i < arrayNumber.length; i++) {
        newArray.push(parseInt(arrayNumber[i], 10));
      }

步骤3

const sumInArray = dataData.reduce( (a, b) => a + b);

最后

console.log(sumInArray);