JavaScript 中有多种方式可以对数组求和,下面列举其中几种:
- for 循环累加:使用 for 循环遍历数组,逐一累加求和。
javascriptCopy codefunction sum(array) {
let total = 0
for (let i = 0; i < array.length; i++) {
total += array[i]
}
return total
}
- reduce 方法:使用 reduce 方法对数组进行累加求和。
javascriptCopy codefunction sum(array) {
return array.reduce((total, current) => total + current, 0)
}
- eval 函数:将数组转换成字符串,使用 eval 函数计算字符串表达式的值。
javascriptCopy codefunction sum(array) {
return eval(array.join('+'))
}
需要注意的是,使用 eval 函数存在一些安全性问题,不建议在生产环境中使用。
- apply 方法:使用 apply 方法将数组作为参数传递给 Math 对象的 sum 方法,实现数组求和。
javascriptCopy codefunction sum(array) {
return Math.sum.apply(null, array)
}
需要注意的是,Math 对象本身并没有 sum 方法,我们需要自己定义。
- ES6 中的 reduce 方法:ES6 中的 reduce 方法支持使用箭头函数进行累加求和。
javascriptCopy codefunction sum(array) {
return array.reduce((total, current) => total + current, 0)
}
总的来说,使用 reduce 方法是最常用的对数组求和的方法,也是最简单和最优雅的写法。