小编典典

如何找到一个数字数组的总和

all

给定一个数组[1, 2, 3, 4],我怎样才能找到它的元素之和?(在这种情况下,总和为10。)

我认为$.each可能有用,但我不确定如何实现它。


阅读 90

收藏
2022-02-25

共1个答案

小编典典

推荐(使用默认值减少)

Array.prototype.reduce可用于遍历数组,将当前元素值与之前元素值的总和相加。

console.log(

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

)

console.log(

  [].reduce((a, b) => a + b, 0)

)

无默认值

你得到一个 TypeError

console.log(

  [].reduce((a, b) => a + b)

)

在 ES6 的箭头函数之前

console.log(

  [1,2,3].reduce(function(acc, val) { return acc + val; }, 0)

)



console.log(

  [].reduce(function(acc, val) { return acc + val; }, 0)

)

非数字输入

如果非数字是可能的输入,您可能想要处理它?

console.log(

  ["hi", 1, 2, "frog"].reduce((a, b) => a + b)

)



let numOr0 = n => isNaN(n) ? 0 : n



console.log(

  ["hi", 1, 2, "frog"].reduce((a, b) =>

    numOr0(a) + numOr0(b))

)

不推荐的 危险 评估使用

我们可以使用eval来执行 JavaScript
代码的字符串表示。使用 Array.prototype.join 函数将数组转换为字符串,我们将 [1,2,3] 更改为“1+2+3”,计算结果为 6。

console.log(

  eval([1,2,3].join('+'))

)



//This way is dangerous if the array is built

// from user input as it may be exploited eg:



eval([1,"2;alert('Malicious code!')"].join('+'))

当然,显示警报并不是可能发生的最糟糕的事情。我将其包含在内的唯一原因是作为 Ortund 问题的答案,因为我认为它没有得到澄清。

2022-02-25