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

How to find the sum of an array of numbers(如何找到一个数字数组的总和)

本文介绍了如何找到一个数字数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)

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

I thought $.each might be useful, but I'm not sure how to implement it.

推荐答案

推荐(减少默认值)

Array.prototype.reduce 可用于遍历数组,将当前元素值添加到先前元素值的总和中.

Recommended (reduce with default value)

Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.

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

你得到一个 TypeError

You get a TypeError

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

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

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

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

If non-numbers are possible inputs, you may want to handle that?

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.

We can use eval to execute a string representation of JavaScript code. Using the Array.prototype.join function to convert the array to a string, we change [1,2,3] into "1+2+3", which evaluates to 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 的问题,因为我认为它没有得到澄清.

Of course displaying an alert isn't the worst thing that could happen. The only reason I have included this is as an answer Ortund's question as I do not think it was clarified.

这篇关于如何找到一个数字数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何找到一个数字数组的总和